home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / text / edit / vim60src.lha / Vim / vim60 / src / getchar.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-09-16  |  103.9 KB  |  4,435 lines

  1. /* vi:set ts=8 sts=4 sw=4:
  2.  *
  3.  * VIM - Vi IMproved    by Bram Moolenaar
  4.  *
  5.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  6.  * Do ":help credits" in Vim to see a list of people who contributed.
  7.  * See README.txt for an overview of the Vim source code.
  8.  */
  9.  
  10. /*
  11.  * getchar.c
  12.  *
  13.  * functions related with getting a character from the user/mapping/redo/...
  14.  *
  15.  * manipulations with redo buffer and stuff buffer
  16.  * mappings and abbreviations
  17.  */
  18.  
  19. #include "vim.h"
  20.  
  21. /*
  22.  * These buffers are used for storing:
  23.  * - stuffed characters: A command that is translated into another command.
  24.  * - redo characters: will redo the last change.
  25.  * - recorded chracters: for the "q" command.
  26.  *
  27.  * The bytes are stored like in the typeahead buffer:
  28.  * - K_SPECIAL introduces a special key (two more bytes follow).  A literal
  29.  *   K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER.
  30.  * - CSI introduces a GUI termcap code (also when gui.in_use is FALSE,
  31.  *   otherwise switching the GUI on would make mappings invalid).
  32.  *   A literal CSI is stored as CSI KS_EXTRA KE_CSI.
  33.  * These translations are also done on multi-byte characters!
  34.  *
  35.  * Escaping CSI bytes is done by the system-specific input functions, called
  36.  * by ui_inchar().
  37.  * Escaping K_SPECIAL is done by inchar().
  38.  * Un-escaping is done by vgetc().
  39.  */
  40.  
  41. /*
  42.  * structure used to store one block of the stuff/redo/recording buffers
  43.  */
  44. struct buffblock
  45. {
  46.     struct buffblock    *b_next;    /* pointer to next buffblock */
  47.     char_u        b_str[1];    /* contents (actually longer) */
  48. };
  49.  
  50. #define MINIMAL_SIZE 20            /* minimal size for b_str */
  51.  
  52. /*
  53.  * header used for the stuff buffer and the redo buffer
  54.  */
  55. struct buffheader
  56. {
  57.     struct buffblock    bh_first;    /* first (dummy) block of list */
  58.     struct buffblock    *bh_curr;    /* buffblock for appending */
  59.     int            bh_index;    /* index for reading */
  60.     int            bh_space;    /* space in bh_curr for appending */
  61. };
  62.  
  63. static struct buffheader stuffbuff = {{NULL, {NUL}}, NULL, 0, 0};
  64. static struct buffheader redobuff = {{NULL, {NUL}}, NULL, 0, 0};
  65. static struct buffheader old_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
  66. #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO)
  67. static struct buffheader save_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
  68. static struct buffheader save_old_redobuff = {{NULL, {NUL}}, NULL, 0, 0};
  69. #endif
  70. static struct buffheader recordbuff = {{NULL, {NUL}}, NULL, 0, 0};
  71.  
  72. static int typeahead_char = 0;        /* typeahead char that's not flushed */
  73.  
  74. /*
  75.  * when block_redo is TRUE redo buffer will not be changed
  76.  * used by edit() to repeat insertions and 'V' command for redoing
  77.  */
  78. static int    block_redo = FALSE;
  79.  
  80. /*
  81.  * Make a hash value for a mapping.
  82.  * "mode" is the lower 4 bits of the State for the mapping.
  83.  * "c1" is the first character of the "lhs".
  84.  * Returns a value between 0 and 255, index in maphash.
  85.  * Put Normal/Visual mode mappings mostly separately from Insert/Cmdline mode.
  86.  */
  87. #define MAP_HASH(mode, c1) (((mode) & (NORMAL + VISUAL + OP_PENDING)) ? (c1) : ((c1) ^ 0x80))
  88.  
  89. /*
  90.  * Each mapping is put in one of the 256 hash lists, to speed up finding it.
  91.  */
  92. static mapblock_T    *(maphash[256]);
  93. static int        maphash_valid = FALSE;
  94.  
  95. /*
  96.  * List used for abbreviations.
  97.  */
  98. static mapblock_T    *first_abbr = NULL; /* first entry in abbrlist */
  99.  
  100. /*
  101.  * variables used by vgetorpeek() and flush_buffers()
  102.  *
  103.  * typebuf.tb_buf[] contains all characters that are not consumed yet.
  104.  * typebuf.tb_buf[typebuf.tb_off] is the first valid character.
  105.  * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len - 1] is the last valid char.
  106.  * typebuf.tb_buf[typebuf.tb_off + typebuf.tb_len] must be NUL.
  107.  * The head of the buffer may contain the result of mappings, abbreviations
  108.  * and @a commands.  The length of this part is typebuf.tb_maplen.
  109.  * typebuf.tb_silent is the part where <silent> applies.
  110.  * After the head are characters that come from the terminal.
  111.  * typebuf.tb_no_abbr_cnt is the number of characters in typebuf.tb_buf that
  112.  * should not be considered for abbreviations.
  113.  * Some parts of typebuf.tb_buf may not be mapped. These parts are remembered
  114.  * in typebuf.tb_noremap[], which is the same length as typebuf.tb_buf and
  115.  * contains RM_NONE for the characters that are not to be remapped.
  116.  * typebuf.tb_noremap[typebuf.tb_off] is the first valid flag.
  117.  * (typebuf has been put in globals.h, because check_termcode() needs it).
  118.  */
  119. #define RM_YES        0    /* tb_noremap: remap */
  120. #define RM_NONE        1    /* tb_noremap: don't remap */
  121. #define RM_SCRIPT    2    /* tb_noremap: remap local script mappings */
  122.  
  123. /* typebuf.tb_buf has three parts: room in front (for result of mappings), the
  124.  * middle for typeahead and room for new characters (which needs to be 3 *
  125.  * MAXMAPLEN) for the Amiga).
  126.  */
  127. #define TYPELEN_INIT    (5 * (MAXMAPLEN + 3))
  128. static char_u    typebuf_init[TYPELEN_INIT];    /* initial typebuf.tb_buf */
  129. static char_u    noremapbuf_init[TYPELEN_INIT];    /* initial typebuf.tb_noremap */
  130.  
  131. static int    last_recorded_len = 0;    /* number of last recorded chars */
  132.  
  133. static void    free_buff __ARGS((struct buffheader *));
  134. static char_u    *get_buffcont __ARGS((struct buffheader *, int));
  135. static void    add_buff __ARGS((struct buffheader *, char_u *, long n));
  136. static void    add_num_buff __ARGS((struct buffheader *, long));
  137. static void    add_char_buff __ARGS((struct buffheader *, int));
  138. static int    read_stuff __ARGS((int advance));
  139. static void    start_stuff __ARGS((void));
  140. static int    read_redo __ARGS((int, int));
  141. static void    copy_redo __ARGS((int));
  142. static void    init_typebuf __ARGS((void));
  143. static void    gotchars __ARGS((char_u *, int));
  144. static void    may_sync_undo __ARGS((void));
  145. static void    closescript __ARGS((void));
  146. static int    vgetorpeek __ARGS((int));
  147. static void    map_free __ARGS((mapblock_T **));
  148. static void    validate_maphash __ARGS((void));
  149. static void    showmap __ARGS((mapblock_T *mp, int local));
  150.  
  151. /*
  152.  * Free and clear a buffer.
  153.  */
  154.     static void
  155. free_buff(buf)
  156.     struct buffheader    *buf;
  157. {
  158.     struct buffblock    *p, *np;
  159.  
  160.     for (p = buf->bh_first.b_next; p != NULL; p = np)
  161.     {
  162.     np = p->b_next;
  163.     vim_free(p);
  164.     }
  165.     buf->bh_first.b_next = NULL;
  166. }
  167.  
  168. /*
  169.  * Return the contents of a buffer as a single string.
  170.  * K_SPECIAL and CSI in the returned string are escaped.
  171.  */
  172.     static char_u *
  173. get_buffcont(buffer, dozero)
  174.     struct buffheader    *buffer;
  175.     int            dozero;        /* count == zero is not an error */
  176. {
  177.     long_u        count = 0;
  178.     char_u        *p = NULL;
  179.     char_u        *p2;
  180.     char_u        *str;
  181.     struct buffblock *bp;
  182.  
  183. /* compute the total length of the string */
  184.     for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
  185.     count += (long_u)STRLEN(bp->b_str);
  186.  
  187.     if ((count || dozero) && (p = lalloc(count + 1, TRUE)) != NULL)
  188.     {
  189.     p2 = p;
  190.     for (bp = buffer->bh_first.b_next; bp != NULL; bp = bp->b_next)
  191.         for (str = bp->b_str; *str; )
  192.         *p2++ = *str++;
  193.     *p2 = NUL;
  194.     }
  195.     return (p);
  196. }
  197.  
  198. /*
  199.  * Return the contents of the record buffer as a single string
  200.  * and clear the record buffer.
  201.  * K_SPECIAL and CSI in the returned string are escaped.
  202.  */
  203.     char_u *
  204. get_recorded()
  205. {
  206.     char_u    *p;
  207.     size_t    len;
  208.  
  209.     p = get_buffcont(&recordbuff, TRUE);
  210.     free_buff(&recordbuff);
  211.  
  212.     /*
  213.      * Remove the characters that were added the last time, these must be the
  214.      * (possibly mapped) characters that stopped the recording.
  215.      */
  216.     len = STRLEN(p);
  217.     if ((int)len >= last_recorded_len)
  218.     {
  219.     len -= last_recorded_len;
  220.     p[len] = NUL;
  221.     }
  222.  
  223.     /*
  224.      * When stopping recording from Insert mode with CTRL-O q, also remove the
  225.      * CTRL-O.
  226.      */
  227.     if (len > 0 && restart_edit != 0 && p[len - 1] == Ctrl_O)
  228.     p[len - 1] = NUL;
  229.  
  230.     return (p);
  231. }
  232.  
  233. /*
  234.  * Return the contents of the redo buffer as a single string.
  235.  * K_SPECIAL and CSI in the returned string are escaped.
  236.  */
  237.     char_u *
  238. get_inserted()
  239. {
  240.     return(get_buffcont(&redobuff, FALSE));
  241. }
  242.  
  243. /*
  244.  * add string "s" after the current block of buffer "buf"
  245.  * K_SPECIAL and CSI should have been escaped already.
  246.  */
  247.     static void
  248. add_buff(buf, s, slen)
  249.     struct buffheader    *buf;
  250.     char_u        *s;
  251.     long        slen;    /* length of "s" or -1 */
  252. {
  253.     struct buffblock *p;
  254.     long_u        len;
  255.  
  256.     if (slen < 0)
  257.     slen = (long)STRLEN(s);
  258.     if (slen == 0)                /* don't add empty strings */
  259.     return;
  260.  
  261.     if (buf->bh_first.b_next == NULL)    /* first add to list */
  262.     {
  263.     buf->bh_space = 0;
  264.     buf->bh_curr = &(buf->bh_first);
  265.     }
  266.     else if (buf->bh_curr == NULL)    /* buffer has already been read */
  267.     {
  268.     EMSG(_("E222: Add to read buffer"));
  269.     return;
  270.     }
  271.     else if (buf->bh_index != 0)
  272.     STRCPY(buf->bh_first.b_next->b_str,
  273.                  buf->bh_first.b_next->b_str + buf->bh_index);
  274.     buf->bh_index = 0;
  275.  
  276.     if (buf->bh_space >= (int)slen)
  277.     {
  278.     len = (long_u)STRLEN(buf->bh_curr->b_str);
  279.     STRNCPY(buf->bh_curr->b_str + len, s, slen);
  280.     buf->bh_curr->b_str[len + slen] = NUL;
  281.     buf->bh_space -= slen;
  282.     }
  283.     else
  284.     {
  285.     if (slen < MINIMAL_SIZE)
  286.         len = MINIMAL_SIZE;
  287.     else
  288.         len = slen;
  289.     p = (struct buffblock *)lalloc((long_u)(sizeof(struct buffblock) + len),
  290.                                     TRUE);
  291.     if (p == NULL)
  292.         return; /* no space, just forget it */
  293.     buf->bh_space = len - slen;
  294.     STRNCPY(p->b_str, s, slen);
  295.     p->b_str[slen] = NUL;
  296.  
  297.     p->b_next = buf->bh_curr->b_next;
  298.     buf->bh_curr->b_next = p;
  299.     buf->bh_curr = p;
  300.     }
  301.     return;
  302. }
  303.  
  304. /*
  305.  * Add number "n" to buffer "buf".
  306.  */
  307.     static void
  308. add_num_buff(buf, n)
  309.     struct buffheader *buf;
  310.     long          n;
  311. {
  312.     char_u    number[32];
  313.  
  314.     sprintf((char *)number, "%ld", n);
  315.     add_buff(buf, number, -1L);
  316. }
  317.  
  318. /*
  319.  * Add character 'c' to buffer "buf".
  320.  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
  321.  */
  322.     static void
  323. add_char_buff(buf, c)
  324.     struct buffheader    *buf;
  325.     int            c;
  326. {
  327. #ifdef FEAT_MBYTE
  328.     char_u    bytes[MB_MAXBYTES + 1];
  329.     int        len;
  330.     int        i;
  331. #endif
  332.     char_u    temp[4];
  333.  
  334. #ifdef FEAT_MBYTE
  335.     if (IS_SPECIAL(c))
  336.     len = 1;
  337.     else
  338.     len = (*mb_char2bytes)(c, bytes);
  339.     for (i = 0; i < len; ++i)
  340.     {
  341.     if (!IS_SPECIAL(c))
  342.         c = bytes[i];
  343. #endif
  344.  
  345.     if (IS_SPECIAL(c) || c == K_SPECIAL || c == NUL)
  346.     {
  347.         /* translate special key code into three byte sequence */
  348.         temp[0] = K_SPECIAL;
  349.         temp[1] = K_SECOND(c);
  350.         temp[2] = K_THIRD(c);
  351.         temp[3] = NUL;
  352.     }
  353. #ifdef FEAT_GUI
  354.     else if (c == CSI)
  355.     {
  356.         /* Translate a CSI to a CSI - KS_EXTRA - KE_CSI sequence */
  357.         temp[0] = CSI;
  358.         temp[1] = KS_EXTRA;
  359.         temp[2] = (int)KE_CSI;
  360.         temp[3] = NUL;
  361.     }
  362. #endif
  363.     else
  364.     {
  365.         temp[0] = c;
  366.         temp[1] = NUL;
  367.     }
  368.     add_buff(buf, temp, -1L);
  369. #ifdef FEAT_MBYTE
  370.     }
  371. #endif
  372. }
  373.  
  374. /*
  375.  * Get one byte from the stuff buffer.
  376.  * If advance == TRUE go to the next char.
  377.  * No translation is done K_SPECIAL and CSI are escaped.
  378.  */
  379.     static int
  380. read_stuff(advance)
  381.     int        advance;
  382. {
  383.     char_u        c;
  384.     struct buffblock    *curr;
  385.  
  386.     if (stuffbuff.bh_first.b_next == NULL)  /* buffer is empty */
  387.     return NUL;
  388.  
  389.     curr = stuffbuff.bh_first.b_next;
  390.     c = curr->b_str[stuffbuff.bh_index];
  391.  
  392.     if (advance)
  393.     {
  394.     if (curr->b_str[++stuffbuff.bh_index] == NUL)
  395.     {
  396.         stuffbuff.bh_first.b_next = curr->b_next;
  397.         vim_free(curr);
  398.         stuffbuff.bh_index = 0;
  399.     }
  400.     }
  401.     return c;
  402. }
  403.  
  404. /*
  405.  * Prepare the stuff buffer for reading (if it contains something).
  406.  */
  407.     static void
  408. start_stuff()
  409. {
  410.     if (stuffbuff.bh_first.b_next != NULL)
  411.     {
  412.     stuffbuff.bh_curr = &(stuffbuff.bh_first);
  413.     stuffbuff.bh_space = 0;
  414.     }
  415. }
  416.  
  417. /*
  418.  * Return TRUE if the stuff buffer is empty.
  419.  */
  420.     int
  421. stuff_empty()
  422. {
  423.     return (stuffbuff.bh_first.b_next == NULL);
  424. }
  425.  
  426. /*
  427.  * Set a typeahead character that won't be flushed.
  428.  */
  429.     void
  430. typeahead_noflush(c)
  431.     int        c;
  432. {
  433.     typeahead_char = c;
  434. }
  435.  
  436. /*
  437.  * Remove the contents of the stuff buffer and the mapped characters in the
  438.  * typeahead buffer (used in case of an error).  If 'typeahead' is true,
  439.  * flush all typeahead characters (used when interrupted by a CTRL-C).
  440.  */
  441.     void
  442. flush_buffers(typeahead)
  443.     int typeahead;
  444. {
  445.     init_typebuf();
  446.  
  447.     start_stuff();
  448.     while (read_stuff(TRUE) != NUL)
  449.     ;
  450.  
  451.     if (typeahead)        /* remove all typeahead */
  452.     {
  453.     /*
  454.      * We have to get all characters, because we may delete the first part
  455.      * of an escape sequence.
  456.      * In an xterm we get one char at a time and we have to get them all.
  457.      */
  458.     while (inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 10L) != 0)
  459.         ;
  460.     typebuf.tb_off = MAXMAPLEN;
  461.     typebuf.tb_len = 0;
  462.     }
  463.     else            /* remove mapped characters only */
  464.     {
  465.     typebuf.tb_off += typebuf.tb_maplen;
  466.     typebuf.tb_len -= typebuf.tb_maplen;
  467.     }
  468.     typebuf.tb_maplen = 0;
  469.     typebuf.tb_silent = 0;
  470.     cmd_silent = FALSE;
  471.     typebuf.tb_no_abbr_cnt = 0;
  472. }
  473.  
  474. /*
  475.  * The previous contents of the redo buffer is kept in old_redobuffer.
  476.  * This is used for the CTRL-O <.> command in insert mode.
  477.  */
  478.     void
  479. ResetRedobuff()
  480. {
  481.     if (!block_redo)
  482.     {
  483.     free_buff(&old_redobuff);
  484.     old_redobuff = redobuff;
  485.     redobuff.bh_first.b_next = NULL;
  486.     }
  487. }
  488.  
  489. #if defined(FEAT_AUTOCMD) || defined(FEAT_EVAL) || defined(PROTO)
  490. /*
  491.  * Save redobuff and old_redobuff to save_redobuff and save_old_redobuff.
  492.  * Used before executing autocommands and user functions.
  493.  */
  494. static int save_level = 0;
  495.  
  496.     void
  497. saveRedobuff()
  498. {
  499.     if (save_level++ == 0)
  500.     {
  501.     save_redobuff = redobuff;
  502.     redobuff.bh_first.b_next = NULL;
  503.     save_old_redobuff = old_redobuff;
  504.     old_redobuff.bh_first.b_next = NULL;
  505.     }
  506. }
  507.  
  508. /*
  509.  * Restore redobuff and old_redobuff from save_redobuff and save_old_redobuff.
  510.  * Used after executing autocommands and user functions.
  511.  */
  512.     void
  513. restoreRedobuff()
  514. {
  515.     if (--save_level == 0)
  516.     {
  517.     free_buff(&redobuff);
  518.     redobuff = save_redobuff;
  519.     free_buff(&old_redobuff);
  520.     old_redobuff = save_old_redobuff;
  521.     }
  522. }
  523. #endif
  524.  
  525. /*
  526.  * Append "s" to the redo buffer.
  527.  * K_SPECIAL and CSI should already have been escaped.
  528.  */
  529.     void
  530. AppendToRedobuff(s)
  531.     char_u       *s;
  532. {
  533.     if (!block_redo)
  534.     add_buff(&redobuff, s, -1L);
  535. }
  536.  
  537. /*
  538.  * Append to Redo buffer literally, escaping special characters with CTRL-V.
  539.  * K_SPECIAL and CSI are escaped as well.
  540.  */
  541.     void
  542. AppendToRedobuffLit(s)
  543.     char_u    *s;
  544. {
  545.     int        c;
  546.     char_u    *start;
  547.  
  548.     if (block_redo)
  549.     return;
  550.  
  551.     while (*s != NUL)
  552.     {
  553.     /* Put a string of normal characters in the redo buffer (that's
  554.      * faster). */
  555.     start = s;
  556.     while (*s >= ' '
  557. #ifndef EBCDIC
  558.         && *s < DEL    /* EBCDIC: all chars above space are normal */
  559. #endif
  560.         )
  561.         ++s;
  562.  
  563.     /* Don't put '0' or '^' as last character, just in case a CTRL-D is
  564.      * typed next. */
  565.     if (*s == NUL && (s[-1] == '0' || s[-1] == '^'))
  566.         --s;
  567.     if (s > start)
  568.         add_buff(&redobuff, start, (long)(s - start));
  569.  
  570.     if (*s != NUL)
  571.     {
  572.         /* Handle a special or multibyte character. */
  573. #ifdef FEAT_MBYTE
  574.         if (has_mbyte)
  575.         c = mb_ptr2char_adv(&s);
  576.         else
  577. #endif
  578.         c = *s++;
  579.         if (c < ' ' || c == DEL || (*s == NUL && (c == '0' || c == '^')))
  580.         add_char_buff(&redobuff, Ctrl_V);
  581.  
  582.         /* CTRL-V '0' must be inserted as CTRL-V 048 (EBCDIC: xf0) */
  583.         if (*s == NUL && c == '0')
  584. #ifdef EBCDIC
  585.         add_buff(&redobuff, (char_u *)"xf0", 3L);
  586. #else
  587.         add_buff(&redobuff, (char_u *)"048", 3L);
  588. #endif
  589.         else
  590.         add_char_buff(&redobuff, c);
  591.     }
  592.     }
  593. }
  594.  
  595. /*
  596.  * Append a character to the redo buffer.
  597.  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
  598.  */
  599.     void
  600. AppendCharToRedobuff(c)
  601.     int           c;
  602. {
  603.     if (!block_redo)
  604.     add_char_buff(&redobuff, c);
  605. }
  606.  
  607. /*
  608.  * Append a number to the redo buffer.
  609.  */
  610.     void
  611. AppendNumberToRedobuff(n)
  612.     long        n;
  613. {
  614.     if (!block_redo)
  615.     add_num_buff(&redobuff, n);
  616. }
  617.  
  618. /*
  619.  * Append string "s" to the stuff buffer.
  620.  * CSI and K_SPECIAL must already have been escaped.
  621.  */
  622.     void
  623. stuffReadbuff(s)
  624.     char_u    *s;
  625. {
  626.     add_buff(&stuffbuff, s, -1L);
  627. }
  628.  
  629.     void
  630. stuffReadbuffLen(s, len)
  631.     char_u    *s;
  632.     long    len;
  633. {
  634.     add_buff(&stuffbuff, s, len);
  635. }
  636.  
  637. #if defined(FEAT_EVAL) || defined(PROTO)
  638. /*
  639.  * Stuff "s" into the stuff buffer, leaving special key codes unmodified and
  640.  * escaping other K_SPECIAL and CSI bytes.
  641.  */
  642.     void
  643. stuffReadbuffSpec(s)
  644.     char_u    *s;
  645. {
  646.     while (*s != NUL)
  647.     {
  648.     if (*s == K_SPECIAL && s[1] != NUL && s[2] != NUL)
  649.     {
  650.         /* Insert special key literally. */
  651.         stuffReadbuffLen(s, 3L);
  652.         s += 3;
  653.     }
  654.     else
  655. #ifdef FEAT_MBYTE
  656.         stuffcharReadbuff(mb_ptr2char_adv(&s));
  657. #else
  658.         stuffcharReadbuff(*s++);
  659. #endif
  660.     }
  661. }
  662. #endif
  663.  
  664. /*
  665.  * Append a character to the stuff buffer.
  666.  * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
  667.  */
  668.     void
  669. stuffcharReadbuff(c)
  670.     int           c;
  671. {
  672.     add_char_buff(&stuffbuff, c);
  673. }
  674.  
  675. /*
  676.  * Append a number to the stuff buffer.
  677.  */
  678.     void
  679. stuffnumReadbuff(n)
  680.     long    n;
  681. {
  682.     add_num_buff(&stuffbuff, n);
  683. }
  684.  
  685. /*
  686.  * Read a character from the redo buffer.  Translates K_SPECIAL, CSI and
  687.  * multibyte characters.
  688.  * The redo buffer is left as it is.
  689.  * if init is TRUE, prepare for redo, return FAIL if nothing to redo, OK
  690.  * otherwise
  691.  * if old is TRUE, use old_redobuff instead of redobuff
  692.  */
  693.     static int
  694. read_redo(init, old_redo)
  695.     int        init;
  696.     int        old_redo;
  697. {
  698.     static struct buffblock    *bp;
  699.     static char_u        *p;
  700.     int                c;
  701. #ifdef FEAT_MBYTE
  702.     int                n;
  703.     char_u            buf[MB_MAXBYTES];
  704.     int                i;
  705. #endif
  706.  
  707.     if (init)
  708.     {
  709.     if (old_redo)
  710.         bp = old_redobuff.bh_first.b_next;
  711.     else
  712.         bp = redobuff.bh_first.b_next;
  713.     if (bp == NULL)
  714.         return FAIL;
  715.     p = bp->b_str;
  716.     return OK;
  717.     }
  718.     if ((c = *p) != NUL)
  719.     {
  720.     /* Reverse the conversion done by add_char_buff() */
  721. #ifdef FEAT_MBYTE
  722.     /* For a multi-byte character get all the bytes and return the
  723.      * converted character. */
  724.     if (has_mbyte && (c != K_SPECIAL || p[1] == KS_SPECIAL))
  725.         n = MB_BYTE2LEN_CHECK(c);
  726.     else
  727.         n = 1;
  728.     for (i = 0; ; ++i)
  729. #endif
  730.     {
  731.         if (c == K_SPECIAL) /* special key or escaped K_SPECIAL */
  732.         {
  733.         c = TO_SPECIAL(p[1], p[2]);
  734.         p += 2;
  735.         }
  736. #ifdef FEAT_GUI
  737.         if (c == CSI)    /* escaped CSI */
  738.         p += 2;
  739. #endif
  740.         if (*++p == NUL && bp->b_next != NULL)
  741.         {
  742.         bp = bp->b_next;
  743.         p = bp->b_str;
  744.         }
  745. #ifdef FEAT_MBYTE
  746.         buf[i] = c;
  747.         if (i == n - 1)    /* last byte of a character */
  748.         {
  749.         if (n != 1)
  750.             c = (*mb_ptr2char)(buf);
  751.         break;
  752.         }
  753.         c = *p;
  754.         if (c == NUL)    /* cannot happen? */
  755.         break;
  756. #endif
  757.     }
  758.     }
  759.  
  760.     return c;
  761. }
  762.  
  763. /*
  764.  * Copy the rest of the redo buffer into the stuff buffer (in a slow way).
  765.  * If old_redo is TRUE, use old_redobuff instead of redobuff.
  766.  * The escaped K_SPECIAL and CSI are copied without translation.
  767.  */
  768.     static void
  769. copy_redo(old_redo)
  770.     int        old_redo;
  771. {
  772.     int        c;
  773.  
  774.     while ((c = read_redo(FALSE, old_redo)) != NUL)
  775.     stuffcharReadbuff(c);
  776. }
  777.  
  778. /*
  779.  * Stuff the redo buffer into the stuffbuff.
  780.  * Insert the redo count into the command.
  781.  * If 'old_redo' is TRUE, the last but one command is repeated
  782.  * instead of the last command (inserting text). This is used for
  783.  * CTRL-O <.> in insert mode
  784.  *
  785.  * return FAIL for failure, OK otherwise
  786.  */
  787.     int
  788. start_redo(count, old_redo)
  789.     long    count;
  790.     int        old_redo;
  791. {
  792.     int        c;
  793.  
  794.     /* init the pointers; return if nothing to redo */
  795.     if (read_redo(TRUE, old_redo) == FAIL)
  796.     return FAIL;
  797.  
  798.     c = read_redo(FALSE, old_redo);
  799.  
  800.     /* copy the buffer name, if present */
  801.     if (c == '"')
  802.     {
  803.     add_buff(&stuffbuff, (char_u *)"\"", 1L);
  804.     c = read_redo(FALSE, old_redo);
  805.  
  806.     /* if a numbered buffer is used, increment the number */
  807.     if (c >= '1' && c < '9')
  808.         ++c;
  809.     add_char_buff(&stuffbuff, c);
  810.     c = read_redo(FALSE, old_redo);
  811.     }
  812.  
  813. #ifdef FEAT_VISUAL
  814.     if (c == 'v')   /* redo Visual */
  815.     {
  816.     VIsual = curwin->w_cursor;
  817.     VIsual_active = TRUE;
  818.     VIsual_select = FALSE;
  819.     VIsual_reselect = TRUE;
  820.     redo_VIsual_busy = TRUE;
  821.     c = read_redo(FALSE, old_redo);
  822.     }
  823. #endif
  824.  
  825.     /* try to enter the count (in place of a previous count) */
  826.     if (count)
  827.     {
  828.     while (isdigit(c))    /* skip "old" count */
  829.         c = read_redo(FALSE, old_redo);
  830.     add_num_buff(&stuffbuff, count);
  831.     }
  832.  
  833.     /* copy from the redo buffer into the stuff buffer */
  834.     add_char_buff(&stuffbuff, c);
  835.     copy_redo(old_redo);
  836.     return OK;
  837. }
  838.  
  839. /*
  840.  * Repeat the last insert (R, o, O, a, A, i or I command) by stuffing
  841.  * the redo buffer into the stuffbuff.
  842.  * return FAIL for failure, OK otherwise
  843.  */
  844.     int
  845. start_redo_ins()
  846. {
  847.     int        c;
  848.  
  849.     if (read_redo(TRUE, FALSE) == FAIL)
  850.     return FAIL;
  851.     start_stuff();
  852.  
  853.     /* skip the count and the command character */
  854.     while ((c = read_redo(FALSE, FALSE)) != NUL)
  855.     {
  856.     if (vim_strchr((char_u *)"AaIiRrOo", c) != NULL)
  857.     {
  858.         if (c == 'O' || c == 'o')
  859.         stuffReadbuff(NL_STR);
  860.         break;
  861.     }
  862.     }
  863.  
  864.     /* copy the typed text from the redo buffer into the stuff buffer */
  865.     copy_redo(FALSE);
  866.     block_redo = TRUE;
  867.     return OK;
  868. }
  869.  
  870.     void
  871. stop_redo_ins()
  872. {
  873.     block_redo = FALSE;
  874. }
  875.  
  876. /*
  877.  * Initialize typebuf.tb_buf to point to typebuf_init.
  878.  * Alloc() cannot be used here: In out-of-memory situations it would
  879.  * be impossible to type anything.
  880.  */
  881.     static void
  882. init_typebuf()
  883. {
  884.     if (typebuf.tb_buf == NULL)
  885.     {
  886.     typebuf.tb_buf = typebuf_init;
  887.     typebuf.tb_noremap = noremapbuf_init;
  888.     typebuf.tb_buflen = TYPELEN_INIT;
  889.     typebuf.tb_len = 0;
  890.     typebuf.tb_off = 0;
  891.     }
  892. }
  893.  
  894. /*
  895.  * insert a string in position 'offset' in the typeahead buffer (for "@r"
  896.  * and ":normal" command, vgetorpeek() and check_termcode())
  897.  *
  898.  * If noremap is REMAP_YES, new string can be mapped again.
  899.  * If noremap is REMAP_NONE, new string cannot be mapped again.
  900.  * If noremap is REMAP_SCRIPT, new string cannot be mapped again, except for
  901.  *            script-local mappings.
  902.  * If noremap is > 0, that many characters of the new string cannot be mapped.
  903.  *
  904.  * If nottyped is TRUE, the string does not return KeyTyped (don't use when
  905.  * offset is non-zero!).
  906.  *
  907.  * If silent is TRUE, cmd_silent is set when the characters are obtained.
  908.  *
  909.  * return FAIL for failure, OK otherwise
  910.  */
  911.     int
  912. ins_typebuf(str, noremap, offset, nottyped, silent)
  913.     char_u    *str;
  914.     int        noremap;
  915.     int        offset;
  916.     int        nottyped;
  917.     int        silent;
  918. {
  919.     char_u    *s1, *s2;
  920.     int        newlen;
  921.     int        addlen;
  922.     int        i;
  923.     int        newoff;
  924.     int        val;
  925.     int        nrm;
  926.  
  927.     init_typebuf();
  928.  
  929.     addlen = (int)STRLEN(str);
  930.     /*
  931.      * Easy case: there is room in front of typebuf.tb_buf[typebuf.tb_off]
  932.      */
  933.     if (offset == 0 && addlen <= typebuf.tb_off)
  934.     {
  935.     typebuf.tb_off -= addlen;
  936.     mch_memmove(typebuf.tb_buf + typebuf.tb_off, str, (size_t)addlen);
  937.     }
  938.     /*
  939.      * Need to allocate new buffer.
  940.      * In typebuf.tb_buf there must always be room for 3 * MAXMAPLEN + 4
  941.      * characters.  We add some extra room to avoid having to allocate too
  942.      * often.
  943.      */
  944.     else
  945.     {
  946.     newoff = MAXMAPLEN + 4;
  947.     newlen = typebuf.tb_len + addlen + newoff + 4 * (MAXMAPLEN + 4);
  948.     if (newlen < 0)            /* string is getting too long */
  949.     {
  950.         EMSG(_(e_toocompl));    /* also calls flush_buffers */
  951.         setcursor();
  952.         return FAIL;
  953.     }
  954.     s1 = alloc(newlen);
  955.     if (s1 == NULL)            /* out of memory */
  956.         return FAIL;
  957.     s2 = alloc(newlen);
  958.     if (s2 == NULL)            /* out of memory */
  959.     {
  960.         vim_free(s1);
  961.         return FAIL;
  962.     }
  963.     typebuf.tb_buflen = newlen;
  964.  
  965.     /* copy the old chars, before the insertion point */
  966.     mch_memmove(s1 + newoff, typebuf.tb_buf + typebuf.tb_off,
  967.                                   (size_t)offset);
  968.     /* copy the new chars */
  969.     mch_memmove(s1 + newoff + offset, str, (size_t)addlen);
  970.     /* copy the old chars, after the insertion point, including the    NUL at
  971.      * the end */
  972.     mch_memmove(s1 + newoff + offset + addlen,
  973.                      typebuf.tb_buf + typebuf.tb_off + offset,
  974.                        (size_t)(typebuf.tb_len - offset + 1));
  975.     if (typebuf.tb_buf != typebuf_init)
  976.         vim_free(typebuf.tb_buf);
  977.     typebuf.tb_buf = s1;
  978.  
  979.     mch_memmove(s2 + newoff, typebuf.tb_noremap + typebuf.tb_off,
  980.                                   (size_t)offset);
  981.     mch_memmove(s2 + newoff + offset + addlen,
  982.            typebuf.tb_noremap + typebuf.tb_off + offset,
  983.                        (size_t)(typebuf.tb_len - offset));
  984.     if (typebuf.tb_noremap != noremapbuf_init)
  985.         vim_free(typebuf.tb_noremap);
  986.     typebuf.tb_noremap = s2;
  987.  
  988.     typebuf.tb_off = newoff;
  989.     }
  990.     typebuf.tb_len += addlen;
  991.  
  992.     /* If noremap == REMAP_SCRIPT: do remap script-local mappings. */
  993.     if (noremap == REMAP_SCRIPT)
  994.     val = RM_SCRIPT;
  995.     else
  996.     val = RM_NONE;
  997.  
  998.     /*
  999.      * Adjust typebuf.tb_noremap[] for the new characters:
  1000.      * If noremap == REMAP_NONE or REMAP_SCRIPT: new characters are
  1001.      *            (sometimes) not remappable
  1002.      * If noremap == REMAP_YES: all the new characters are mappable
  1003.      * If noremap  > 0: "noremap" characters are not remappable, the rest
  1004.      *            mappable
  1005.      */
  1006.     if (noremap < 0)
  1007.     nrm = addlen;
  1008.     else
  1009.     nrm = noremap;
  1010.     for (i = 0; i < addlen; ++i)
  1011.     typebuf.tb_noremap[typebuf.tb_off + i + offset] =
  1012.                           (--nrm >= 0) ? val : RM_YES;
  1013.  
  1014.     /* tb_maplen and tb_silent only remember the length of mapped and/or
  1015.      * silent mappings at the start of the buffer, assuming that a mapped
  1016.      * sequence doesn't result in typed characters. */
  1017.     if (nottyped || typebuf.tb_maplen > offset)
  1018.     typebuf.tb_maplen += addlen;
  1019.     if (silent || typebuf.tb_silent > offset)
  1020.     {
  1021.     typebuf.tb_silent += addlen;
  1022.     cmd_silent = TRUE;
  1023.     }
  1024.     if (typebuf.tb_no_abbr_cnt && offset == 0)    /* and not used for abbrev.s */
  1025.     typebuf.tb_no_abbr_cnt += addlen;
  1026.  
  1027.     return OK;
  1028. }
  1029.  
  1030. /*
  1031.  * Return TRUE if there are no characters in the typeahead buffer that have
  1032.  * not been typed (result from a mapping or come from ":normal").
  1033.  */
  1034.     int
  1035. typebuf_typed()
  1036. {
  1037.     return typebuf.tb_maplen == 0;
  1038. }
  1039.  
  1040. /*
  1041.  * Return the number of characters that are mapped (or not typed).
  1042.  */
  1043.     int
  1044. typebuf_maplen()
  1045. {
  1046.     return typebuf.tb_maplen;
  1047. }
  1048.  
  1049. /*
  1050.  * remove "len" characters from typebuf.tb_buf[typebuf.tb_off + offset]
  1051.  */
  1052.     void
  1053. del_typebuf(len, offset)
  1054.     int    len;
  1055.     int    offset;
  1056. {
  1057.     int        i;
  1058.  
  1059.     typebuf.tb_len -= len;
  1060.     /*
  1061.      * Easy case: Just increase typebuf.tb_off.
  1062.      */
  1063.     if (offset == 0 && typebuf.tb_buflen - (typebuf.tb_off + len)
  1064.                              >= 3 * MAXMAPLEN + 3)
  1065.     typebuf.tb_off += len;
  1066.     /*
  1067.      * Have to move the characters in typebuf.tb_buf[] and typebuf.tb_noremap[]
  1068.      */
  1069.     else
  1070.     {
  1071.     i = typebuf.tb_off + offset;
  1072.     /*
  1073.      * Leave some extra room at the end to avoid reallocation.
  1074.      */
  1075.     if (typebuf.tb_off > MAXMAPLEN)
  1076.     {
  1077.         mch_memmove(typebuf.tb_buf + MAXMAPLEN,
  1078.                  typebuf.tb_buf + typebuf.tb_off, (size_t)offset);
  1079.         mch_memmove(typebuf.tb_noremap + MAXMAPLEN,
  1080.              typebuf.tb_noremap + typebuf.tb_off, (size_t)offset);
  1081.         typebuf.tb_off = MAXMAPLEN;
  1082.     }
  1083.     /* adjust typebuf.tb_buf (include the NUL at the end) */
  1084.     mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset,
  1085.                              typebuf.tb_buf + i + len,
  1086.                        (size_t)(typebuf.tb_len - offset + 1));
  1087.     /* adjust typebuf.tb_noremap[] */
  1088.     mch_memmove(typebuf.tb_noremap + typebuf.tb_off + offset,
  1089.                          typebuf.tb_noremap + i + len,
  1090.                        (size_t)(typebuf.tb_len - offset));
  1091.     }
  1092.  
  1093.     if (typebuf.tb_maplen > offset)        /* adjust tb_maplen */
  1094.     {
  1095.     if (typebuf.tb_maplen < offset + len)
  1096.         typebuf.tb_maplen = offset;
  1097.     else
  1098.         typebuf.tb_maplen -= len;
  1099.     }
  1100.     if (typebuf.tb_silent > offset)        /* adjust tb_silent */
  1101.     {
  1102.     if (typebuf.tb_silent < offset + len)
  1103.         typebuf.tb_silent = offset;
  1104.     else
  1105.         typebuf.tb_silent -= len;
  1106.     }
  1107.     if (typebuf.tb_no_abbr_cnt > offset)    /* adjust tb_no_abbr_cnt */
  1108.     {
  1109.     if (typebuf.tb_no_abbr_cnt < offset + len)
  1110.         typebuf.tb_no_abbr_cnt = offset;
  1111.     else
  1112.         typebuf.tb_no_abbr_cnt -= len;
  1113.     }
  1114. }
  1115.  
  1116. /*
  1117.  * Write typed characters to script file.
  1118.  * If recording is on put the character in the recordbuffer.
  1119.  */
  1120.     static void
  1121. gotchars(s, len)
  1122.     char_u    *s;
  1123.     int        len;
  1124. {
  1125.     int        c;
  1126.     char_u    buf[2];
  1127.  
  1128.     /* remember how many chars were last recorded */
  1129.     if (Recording)
  1130.     last_recorded_len += len;
  1131.  
  1132.     buf[1] = NUL;
  1133.     while (len--)
  1134.     {
  1135.     /* Handle one byte at a time; no translation to be done. */
  1136.     c = *s++;
  1137.     updatescript(c);
  1138.  
  1139.     if (Recording)
  1140.     {
  1141.         buf[0] = c;
  1142.         add_buff(&recordbuff, buf, 1L);
  1143.     }
  1144.     }
  1145.     may_sync_undo();
  1146.  
  1147. #ifdef FEAT_EVAL
  1148.     /* output "debug mode" message next time in debug mode */
  1149.     debug_did_msg = FALSE;
  1150. #endif
  1151.  
  1152.     /* Since characters have been typed, consider the following to be in
  1153.      * another mapping.  Search string will be kept in history. */
  1154.     ++maptick;
  1155. }
  1156.  
  1157. /*
  1158.  * Sync undo.  Called when typed characters are obtained from the typeahead
  1159.  * buffer, or when a menu is used.
  1160.  * Do not sync:
  1161.  * - In Insert mode, unless cursor key has been used.
  1162.  * - While reading a script file.
  1163.  * - When no_u_sync is non-zero.
  1164.  */
  1165.     static void
  1166. may_sync_undo()
  1167. {
  1168.     if ((!(State & (INSERT + CMDLINE)) || arrow_used)
  1169.         && scriptin[curscript] == NULL && !no_u_sync)
  1170.     u_sync();
  1171. }
  1172.  
  1173. /*
  1174.  * Make "typebuf" empty and allocate new buffers.
  1175.  * Returns FAIL when out of memory.
  1176.  */
  1177.     int
  1178. alloc_typebuf()
  1179. {
  1180.     typebuf.tb_buf = alloc(TYPELEN_INIT);
  1181.     typebuf.tb_noremap = alloc(TYPELEN_INIT);
  1182.     if (typebuf.tb_buf == NULL || typebuf.tb_noremap == NULL)
  1183.     {
  1184.     free_typebuf();
  1185.     return FAIL;
  1186.     }
  1187.     typebuf.tb_buflen = TYPELEN_INIT;
  1188.     typebuf.tb_off = 0;
  1189.     typebuf.tb_len = 0;
  1190.     typebuf.tb_maplen = 0;
  1191.     typebuf.tb_silent = 0;
  1192.     typebuf.tb_no_abbr_cnt = 0;
  1193.     return OK;
  1194. }
  1195.  
  1196. /*
  1197.  * Free the buffers of "typebuf".
  1198.  */
  1199.     void
  1200. free_typebuf()
  1201. {
  1202.     vim_free(typebuf.tb_buf);
  1203.     vim_free(typebuf.tb_noremap);
  1204. }
  1205.  
  1206. /*
  1207.  * When doing ":so! file", the current typeahead needs to be saved, and
  1208.  * restored when "file" has been read completely.
  1209.  */
  1210. static typebuf_T saved_typebuf[NSCRIPT];
  1211.  
  1212.     int
  1213. save_typebuf()
  1214. {
  1215.     init_typebuf();
  1216.     saved_typebuf[curscript] = typebuf;
  1217.     /* If out of memory: restore typebuf and close file. */
  1218.     if (alloc_typebuf() == FAIL)
  1219.     {
  1220.     closescript();
  1221.     return FAIL;
  1222.     }
  1223.     return OK;
  1224. }
  1225.  
  1226. /*
  1227.  * open new script file for ":so!" command
  1228.  * return OK on success, FAIL on error
  1229.  */
  1230.     int
  1231. openscript(name)
  1232.     char_u *name;
  1233. {
  1234.     int        oldcurscript;
  1235.     oparg_T    oa;
  1236.     int        save_State;
  1237.  
  1238.     if (curscript + 1 == NSCRIPT)
  1239.     {
  1240.     EMSG(_(e_nesting));
  1241.     return FAIL;
  1242.     }
  1243.  
  1244.     if (scriptin[curscript] != NULL)    /* already reading script */
  1245.     ++curscript;
  1246.                 /* use NameBuff for expanded name */
  1247.     expand_env(name, NameBuff, MAXPATHL);
  1248.     if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
  1249.     {
  1250.     EMSG2(_(e_notopen), name);
  1251.     if (curscript)
  1252.         --curscript;
  1253.     return FAIL;
  1254.     }
  1255.     if (save_typebuf() == FAIL)
  1256.     return FAIL;
  1257.  
  1258.     /*
  1259.      * With command ":g/pat/so! file" we have to execute the
  1260.      * commands from the file now.
  1261.      */
  1262.     if (global_busy)
  1263.     {
  1264.     clear_oparg(&oa);
  1265.     save_State = State;
  1266.     State = NORMAL;
  1267.     oldcurscript = curscript;
  1268.     do
  1269.     {
  1270.         check_cursor();    /* put cursor on an existing line */
  1271.         normal_cmd(&oa, FALSE);
  1272.         vpeekc();        /* check for end of file */
  1273.     }
  1274.     while (scriptin[oldcurscript] != NULL);
  1275.     State = save_State;
  1276.     }
  1277.  
  1278.     return OK;
  1279. }
  1280.  
  1281. /*
  1282.  * Close the currently active input script.
  1283.  */
  1284.     static void
  1285. closescript()
  1286. {
  1287.     free_typebuf();
  1288.     typebuf = saved_typebuf[curscript];
  1289.  
  1290.     fclose(scriptin[curscript]);
  1291.     scriptin[curscript] = NULL;
  1292.     if (curscript > 0)
  1293.     --curscript;
  1294. }
  1295.  
  1296. #if defined(FEAT_INS_EXPAND) || defined(PROTO)
  1297. /*
  1298.  * Return TRUE when reading keys from a script file.
  1299.  */
  1300.     int
  1301. using_script()
  1302. {
  1303.     return scriptin[curscript] != NULL;
  1304. }
  1305. #endif
  1306.  
  1307. /*
  1308.  * updatescipt() is called when a character can be written into the script file
  1309.  * or when we have waited some time for a character (c == 0)
  1310.  *
  1311.  * All the changed memfiles are synced if c == 0 or when the number of typed
  1312.  * characters reaches 'updatecount' and 'updatecount' is non-zero.
  1313.  */
  1314.     void
  1315. updatescript(c)
  1316.     int c;
  1317. {
  1318.     static int        count = 0;
  1319.  
  1320.     if (c && scriptout)
  1321.     putc(c, scriptout);
  1322.     if (c == 0 || (p_uc > 0 && ++count >= p_uc))
  1323.     {
  1324.     ml_sync_all(c == 0, TRUE);
  1325.     count = 0;
  1326.     }
  1327. }
  1328.  
  1329. #define KL_PART_KEY -1        /* keylen value for incomplete key-code */
  1330. #define KL_PART_MAP -2        /* keylen value for incomplete mapping */
  1331.  
  1332. static int old_char = -1;    /* character put back by vungetc() */
  1333. static int old_mod_mask;    /* mod_mask for ungotten character */
  1334.  
  1335. /*
  1336.  * Get the next input character.
  1337.  * Can return a special key or a multi-byte character.
  1338.  * Can return NUL when called recursively, use safe_vgetc() if that's not
  1339.  * wanted.
  1340.  * This translates escaped K_SPECIAL and CSI bytes to a K_SPECIAL or CSI byte.
  1341.  * Collects the bytes of a multibyte character into the whole character.
  1342.  * Returns the modifers in the global "mod_mask".
  1343.  */
  1344.     int
  1345. vgetc()
  1346. {
  1347.     int        c, c2;
  1348. #ifdef FEAT_MBYTE
  1349.     int        n;
  1350.     char_u    buf[MB_MAXBYTES];
  1351.     int        i;
  1352. #endif
  1353.  
  1354.     /*
  1355.      * If a character was put back with vungetc, it was already processed.
  1356.      * Return it directly.
  1357.      */
  1358.     if (old_char != -1)
  1359.     {
  1360.     c = old_char;
  1361.     old_char = -1;
  1362.     mod_mask = old_mod_mask;
  1363.     return c;
  1364.     }
  1365.  
  1366.     mod_mask = 0x0;
  1367.     last_recorded_len = 0;
  1368.     for (;;)            /* this is done twice if there are modifiers */
  1369.     {
  1370.     if (mod_mask)        /* no mapping after modifier has been read */
  1371.     {
  1372.         ++no_mapping;
  1373.         ++allow_keys;
  1374.     }
  1375.     c = vgetorpeek(TRUE);
  1376.     if (mod_mask)
  1377.     {
  1378.         --no_mapping;
  1379.         --allow_keys;
  1380.     }
  1381.  
  1382.     /* Get two extra bytes for special keys */
  1383.     if (c == K_SPECIAL
  1384. #ifdef FEAT_GUI
  1385.         || c == CSI
  1386. #endif
  1387.        )
  1388.     {
  1389.         ++no_mapping;
  1390.         c2 = vgetorpeek(TRUE);    /* no mapping for these chars */
  1391.         c = vgetorpeek(TRUE);
  1392.         --no_mapping;
  1393.         if (c2 == KS_MODIFIER)
  1394.         {
  1395.         mod_mask = c;
  1396.         continue;
  1397.         }
  1398.         c = TO_SPECIAL(c2, c);
  1399.  
  1400. #if defined(FEAT_GUI_W32) && defined(FEAT_MENU) && defined(FEAT_TEAROFF)
  1401.         /* Handle K_TEAROFF here, the caller of vgetc() doesn't need to
  1402.          * know that a menu was torn off */
  1403.         if (c == K_TEAROFF)
  1404.         {
  1405.         char_u    name[200];
  1406.         int    i;
  1407.  
  1408.         /* get menu path, it ends with a <CR> */
  1409.         for (i = 0; (c = vgetorpeek(TRUE)) != '\r'; )
  1410.         {
  1411.             name[i] = c;
  1412.             if (i < 199)
  1413.             ++i;
  1414.         }
  1415.         name[i] = NUL;
  1416.         gui_make_tearoff(name);
  1417.         continue;
  1418.         }
  1419. #endif
  1420. #ifdef FEAT_GUI
  1421.         /* Translate K_CSI to CSI.  The special key is only used to avoid
  1422.          * it being recognized as the start of a special key. */
  1423.         if (c == K_CSI)
  1424.         c = CSI;
  1425. #endif
  1426.     }
  1427. #ifdef MSDOS
  1428.     /*
  1429.      * If K_NUL was typed, it is replaced by K_NUL, 3 in mch_inchar().
  1430.      * Delete the 3 here.
  1431.      */
  1432.     else if (c == K_NUL && vpeekc() == 3)
  1433.         (void)vgetorpeek(TRUE);
  1434. #endif
  1435.  
  1436.     if (c >= FIRST_KEYPAD && c <= LAST_KEYPAD)
  1437.     {
  1438.         /* a keypad key was not mapped, use it like its ASCII equivalent */
  1439.         switch (c)
  1440.         {
  1441.         case K_KPLUS:        c = '+'; break;
  1442.         case K_KMINUS:        c = '-'; break;
  1443.         case K_KDIVIDE:        c = '/'; break;
  1444.         case K_KMULTIPLY:    c = '*'; break;
  1445.         case K_KENTER:        c = CR; break;
  1446.         case K_KPOINT:        c = '.'; break;
  1447.         case K_K0:        c = '0'; break;
  1448.         case K_K1:        c = '1'; break;
  1449.         case K_K2:        c = '2'; break;
  1450.         case K_K3:        c = '3'; break;
  1451.         case K_K4:        c = '4'; break;
  1452.         case K_K5:        c = '5'; break;
  1453.         case K_K6:        c = '6'; break;
  1454.         case K_K7:        c = '7'; break;
  1455.         case K_K8:        c = '8'; break;
  1456.         case K_K9:        c = '9'; break;
  1457.         }
  1458.     }
  1459.  
  1460. #ifdef FEAT_MBYTE
  1461.     /* For a multi-byte character get all the bytes and return the
  1462.      * converted character.
  1463.      * Note: This will loop until enough bytes are received!
  1464.      */
  1465.     if (has_mbyte && (n = MB_BYTE2LEN_CHECK(c)) > 1)
  1466.     {
  1467.         ++no_mapping;
  1468.         buf[0] = c;
  1469.         for (i = 1; i < n; ++i)
  1470.         {
  1471.         buf[i] = vgetorpeek(TRUE);
  1472.         if (buf[i] == K_SPECIAL
  1473. #ifdef FEAT_GUI
  1474.             || buf[i] == CSI
  1475. #endif
  1476.             )
  1477.         {
  1478.             /* Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence,
  1479.              * which represents a K_SPECIAL (0x80),
  1480.              * or a CSI - KS_EXTRA - KE_CSI sequence, which represents
  1481.              * a CSI (0x9B),
  1482.              * of a K_SPECIAL - KS_EXTRA - KE_CSI, which is CSI too. */
  1483.             c = vgetorpeek(TRUE);
  1484.             if (vgetorpeek(TRUE) == (int)KE_CSI && c == KS_EXTRA)
  1485.             buf[i] = CSI;
  1486.         }
  1487.         }
  1488.         --no_mapping;
  1489.         c = (*mb_ptr2char)(buf);
  1490.     }
  1491. #endif
  1492.  
  1493.     return c;
  1494.     }
  1495. }
  1496.  
  1497. /*
  1498.  * Like vgetc(), but never return a NUL when called recursively, get a key
  1499.  * directly from the user (ignoring typeahead).
  1500.  */
  1501.     int
  1502. safe_vgetc()
  1503. {
  1504.     int    c;
  1505.  
  1506.     c = vgetc();
  1507.     if (c == NUL)
  1508.     c = get_keystroke();
  1509.     return c;
  1510. }
  1511.  
  1512. /*
  1513.  * Check if a character is available, such that vgetc() will not block.
  1514.  * If the next character is a special character or multi-byte, the returned
  1515.  * character is not valid!.
  1516.  */
  1517.     int
  1518. vpeekc()
  1519. {
  1520.     if (old_char != -1)
  1521.     return old_char;
  1522.     return vgetorpeek(FALSE);
  1523. }
  1524.  
  1525. #if defined(FEAT_TERMRESPONSE) || defined(PROTO)
  1526. /*
  1527.  * Like vpeekc(), but don't allow mapping.  Do allow checking for terminal
  1528.  * codes.
  1529.  */
  1530.     int
  1531. vpeekc_nomap()
  1532. {
  1533.     int        c;
  1534.  
  1535.     ++no_mapping;
  1536.     ++allow_keys;
  1537.     c = vpeekc();
  1538.     --no_mapping;
  1539.     --allow_keys;
  1540.     return c;
  1541. }
  1542. #endif
  1543.  
  1544. #if defined(FEAT_INS_EXPAND) || defined(PROTO)
  1545. /*
  1546.  * Check if any character is available, also half an escape sequence.
  1547.  * Trick: when no typeahead found, but there is something in the typeahead
  1548.  * buffer, it must be an ESC that is recognized as the start of a key code.
  1549.  */
  1550.     int
  1551. vpeekc_any()
  1552. {
  1553.     int        c;
  1554.  
  1555.     c = vpeekc();
  1556.     if (c == NUL && typebuf.tb_len > 0)
  1557.     c = ESC;
  1558.     return c;
  1559. }
  1560. #endif
  1561.  
  1562. /*
  1563.  * Call vpeekc() without causing anything to be mapped.
  1564.  * Return TRUE if a character is available, FALSE otherwise.
  1565.  */
  1566.     int
  1567. char_avail()
  1568. {
  1569.     int        retval;
  1570.  
  1571.     ++no_mapping;
  1572.     retval = vpeekc();
  1573.     --no_mapping;
  1574.     return (retval != NUL);
  1575. }
  1576.  
  1577.     void
  1578. vungetc(c)    /* unget one character (can only be done once!) */
  1579.     int        c;
  1580. {
  1581.     old_char = c;
  1582.     old_mod_mask = mod_mask;
  1583. }
  1584.  
  1585. /*
  1586.  * get a character:
  1587.  * 1. from the stuffbuffer
  1588.  *    This is used for abbreviated commands like "D" -> "d$".
  1589.  *    Also used to redo a command for ".".
  1590.  * 2. from the typeahead buffer
  1591.  *    Stores text obtained previously but not used yet.
  1592.  *    Also stores the result of mappings.
  1593.  *    Also used for the ":normal" command.
  1594.  * 3. from the user
  1595.  *    This may do a blocking wait if "advance" is TRUE.
  1596.  *
  1597.  * if "advance" is TRUE (vgetc()):
  1598.  *    really get the character.
  1599.  *    KeyTyped is set to TRUE in the case the user typed the key.
  1600.  *    KeyStuffed is TRUE if the character comes from the stuff buffer.
  1601.  * if "advance" is FALSE (vpeekc()):
  1602.  *    just look whether there is a character available.
  1603.  *
  1604.  * When "no_mapping" is zero, checks for mappings in the current mode.
  1605.  * Only returns one byte (of a multi-byte character).
  1606.  * K_SPECIAL and CSI may be escaped, need to get two more bytes then.
  1607.  */
  1608.     static int
  1609. vgetorpeek(advance)
  1610.     int        advance;
  1611. {
  1612.     int        c, c1;
  1613.     int        keylen;
  1614.     char_u    *s;
  1615.     mapblock_T    *mp;
  1616. #ifdef FEAT_LOCALMAP
  1617.     mapblock_T    *mp2;
  1618. #endif
  1619.     mapblock_T    *mp_match;
  1620.     int        mp_match_len = 0;
  1621.     int        timedout = FALSE;        /* waited for more than 1 second
  1622.                         for mapping to complete */
  1623.     int        mapdepth = 0;        /* check for recursive mapping */
  1624.     int        mode_deleted = FALSE;   /* set when mode has been deleted */
  1625.     int        local_State;
  1626.     int        mlen;
  1627.     int        max_mlen;
  1628. #ifdef FEAT_CMDL_INFO
  1629.     int        i;
  1630.     int        new_wcol, new_wrow;
  1631. #endif
  1632. #ifdef FEAT_GUI
  1633. # ifdef FEAT_MENU
  1634.     int        idx;
  1635. # endif
  1636.     int        shape_changed = FALSE;  /* adjusted cursor shape */
  1637. #endif
  1638.     int        n;
  1639. #ifdef FEAT_LANGMAP
  1640.     int        nolmaplen;
  1641. #endif
  1642.     int        old_wcol, old_wrow;
  1643.  
  1644.     /*
  1645.      * This function doesn't work very well when called recursively.  This may
  1646.      * happen though, because of:
  1647.      * 1. The call to add_to_showcmd().    char_avail() is then used to check if
  1648.      * there is a character available, which calls this function.  In that
  1649.      * case we must return NUL, to indicate no character is available.
  1650.      * 2. A GUI callback function writes to the screen, causing a
  1651.      * wait_return().
  1652.      * Using ":normal" can also do this, but it saves the typeahead buffer,
  1653.      * thus it should be OK.  But don't get a key from the user then.
  1654.      */
  1655.     if (vgetc_busy
  1656. #ifdef FEAT_EX_EXTRA
  1657.         && ex_normal_busy == 0
  1658. #endif
  1659.         )
  1660.     return NUL;
  1661.  
  1662.     local_State = get_real_state();
  1663.  
  1664.     vgetc_busy = TRUE;
  1665.  
  1666.     if (advance)
  1667.     KeyStuffed = FALSE;
  1668.  
  1669.     init_typebuf();
  1670.     start_stuff();
  1671.     if (advance && typebuf.tb_maplen == 0)
  1672.     Exec_reg = FALSE;
  1673.     do
  1674.     {
  1675. /*
  1676.  * get a character: 1. from the stuffbuffer
  1677.  */
  1678.     if (typeahead_char != 0)
  1679.     {
  1680.         c = typeahead_char;
  1681.         if (advance)
  1682.         typeahead_char = 0;
  1683.     }
  1684.     else
  1685.         c = read_stuff(advance);
  1686.     if (c != NUL && !got_int)
  1687.     {
  1688.         if (advance)
  1689.         {
  1690.         /* KeyTyped = FALSE;  When the command that stuffed something
  1691.          * was typed, behave like the stuffed command was typed.
  1692.          * needed for CTRL-W CTRl-] to open a fold, for example. */
  1693.         KeyStuffed = TRUE;
  1694.         }
  1695.         if (typebuf.tb_no_abbr_cnt == 0)
  1696.         typebuf.tb_no_abbr_cnt = 1;    /* no abbreviations now */
  1697.     }
  1698.     else
  1699.     {
  1700.         /*
  1701.          * Loop until we either find a matching mapped key, or we
  1702.          * are sure that it is not a mapped key.
  1703.          * If a mapped key sequence is found we go back to the start to
  1704.          * try re-mapping.
  1705.          */
  1706.         for (;;)
  1707.         {
  1708.         /*
  1709.          * ui_breakcheck() is slow, don't use it too often when
  1710.          * inside a mapping.  But call it each time for typed
  1711.          * characters.
  1712.          */
  1713.         if (typebuf.tb_maplen)
  1714.             line_breakcheck();
  1715.         else
  1716.             ui_breakcheck();        /* check for CTRL-C */
  1717.         keylen = 0;
  1718.         if (got_int)
  1719.         {
  1720.             /* flush all input */
  1721.             c = inchar(typebuf.tb_buf, typebuf.tb_buflen - 1, 0L);
  1722.             /*
  1723.              * If inchar returns TRUE (script file was active) or we
  1724.              * are inside a mapping, get out of insert mode.
  1725.              * Otherwise we behave like having gotten a CTRL-C.
  1726.              * As a result typing CTRL-C in insert mode will
  1727.              * really insert a CTRL-C.
  1728.              */
  1729.             if ((c || typebuf.tb_maplen)
  1730.                           && (State & (INSERT + CMDLINE)))
  1731.             c = ESC;
  1732.             else
  1733.             c = Ctrl_C;
  1734.             flush_buffers(TRUE);    /* flush all typeahead */
  1735.  
  1736.             /* Also record this character, it might be needed to
  1737.              * get out of Insert mode. */
  1738.             *typebuf.tb_buf = c;
  1739.             gotchars(typebuf.tb_buf, 1);
  1740.             cmd_silent = FALSE;
  1741.  
  1742.             break;
  1743.         }
  1744.         else if (typebuf.tb_len > 0)
  1745.         {
  1746.             /*
  1747.              * Check for a mappable key sequence.
  1748.              * Walk through one maphash[] list until we find an
  1749.              * entry that matches.
  1750.              *
  1751.              * Don't look for mappings if:
  1752.              * - no_mapping set: mapping disabled (e.g. for CTRL-V)
  1753.              * - maphash_valid not set: no mappings present.
  1754.              * - typebuf.tb_buf[typebuf.tb_off] should not be remapped
  1755.              * - in insert or cmdline mode and 'paste' option set
  1756.              * - waiting for "hit return to continue" and CR or SPACE
  1757.              *     typed
  1758.              * - waiting for a char with --more--
  1759.              * - in Ctrl-X mode, and we get a valid char for that mode
  1760.              */
  1761.             mp = NULL;
  1762.             max_mlen = 0;
  1763.             if (no_mapping == 0 && maphash_valid
  1764.                 && (typebuf.tb_maplen == 0
  1765.                 || (p_remap
  1766.                     && typebuf.tb_noremap[typebuf.tb_off]
  1767.                                   != RM_NONE))
  1768.                 && !(p_paste && (State & (INSERT + CMDLINE)))
  1769.                 && !(State == HITRETURN
  1770.                 && (typebuf.tb_buf[typebuf.tb_off] == CR
  1771.                     || typebuf.tb_buf[typebuf.tb_off] == ' '))
  1772.                 && State != ASKMORE
  1773.                 && State != CONFIRM
  1774. #ifdef FEAT_INS_EXPAND
  1775.                 && !(ctrl_x_mode && vim_is_ctrl_x_key(
  1776.                           typebuf.tb_buf[typebuf.tb_off]))
  1777. #endif
  1778.                 )
  1779.             {
  1780.             c1 = typebuf.tb_buf[typebuf.tb_off];
  1781. #ifdef FEAT_LANGMAP
  1782.             if (c1 == K_SPECIAL)
  1783.                 nolmaplen = 2;
  1784.             else
  1785.             {
  1786.                 LANGMAP_ADJUST(c1, TRUE);
  1787.                 nolmaplen = 0;
  1788.             }
  1789. #endif
  1790. #ifdef FEAT_LOCALMAP
  1791.             /* First try buffer-local mappings. */
  1792.             mp = curbuf->b_maphash[MAP_HASH(local_State, c1)];
  1793.             mp2 = maphash[MAP_HASH(local_State, c1)];
  1794.             if (mp == NULL)
  1795.             {
  1796.                 mp = mp2;
  1797.                 mp2 = NULL;
  1798.             }
  1799. #else
  1800.             mp = maphash[MAP_HASH(local_State, c1)];
  1801. #endif
  1802.             /*
  1803.              * Loop until a partly matching mapping is found or
  1804.              * all (local) mappings have been checked.
  1805.              * The longest full match is remembered in "mp_match".
  1806.              * A full match is only accepted if there is no partly
  1807.              * match, so "aa" and "aaa" can both be mapped.
  1808.              */
  1809.             mp_match = NULL;
  1810.             mp_match_len = 0;
  1811.             for ( ; mp != NULL;
  1812. #ifdef FEAT_LOCALMAP
  1813.                 mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
  1814. #endif
  1815.                 (mp = mp->m_next))
  1816.             {
  1817.                 /*
  1818.                  * Only consider an entry if the first character
  1819.                  * matches and it is for the current state.
  1820.                  * Skip ":lmap" mappings if keys were mapped.
  1821.                  */
  1822.                 if (mp->m_keys[0] == c1
  1823.                     && (mp->m_mode & local_State)
  1824.                     && ((mp->m_mode & LANGMAP) == 0
  1825.                     || typebuf.tb_maplen == 0))
  1826.                 {
  1827. #ifdef FEAT_LANGMAP
  1828.                 int    nomap = nolmaplen;
  1829.                 int    c2;
  1830. #endif
  1831.                 /* find the match length of this mapping */
  1832.                 for (mlen = 1; mlen < typebuf.tb_len; ++mlen)
  1833.                 {
  1834. #ifdef FEAT_LANGMAP
  1835.                     c2 = typebuf.tb_buf[typebuf.tb_off + mlen];
  1836.                     if (nomap > 0)
  1837.                     --nomap;
  1838.                     else if (c2 == K_SPECIAL)
  1839.                     nomap = 2;
  1840.                     else
  1841.                     LANGMAP_ADJUST(c2, TRUE);
  1842.                     if (mp->m_keys[mlen] != c2)
  1843. #else
  1844.                     if (mp->m_keys[mlen] !=
  1845.                     typebuf.tb_buf[typebuf.tb_off + mlen])
  1846. #endif
  1847.                     break;
  1848.                 }
  1849.  
  1850. #ifdef FEAT_MBYTE
  1851.                 /* Don't allow mapping the first byte(s) of a
  1852.                  * multi-byte char.  Happens when mapping
  1853.                  * <M-a> and then changing 'encoding'. */
  1854.                 if (has_mbyte && MB_BYTE2LEN(c1)
  1855.                         > (*mb_ptr2len_check)(mp->m_keys))
  1856.                     mlen = 0;
  1857. #endif
  1858.                 /*
  1859.                  * Check an entry whether it matches.
  1860.                  * - Full match: mlen == keylen
  1861.                  * - Partly match: mlen == typebuf.tb_len
  1862.                  */
  1863.                 keylen = mp->m_keylen;
  1864.                 if (mlen == keylen
  1865.                      || (mlen == typebuf.tb_len
  1866.                           && typebuf.tb_len < keylen))
  1867.                 {
  1868.                     /*
  1869.                      * If only script-local mappings are
  1870.                      * allowed, check if the mapping starts
  1871.                      * with K_SNR.
  1872.                      */
  1873.                     s = typebuf.tb_noremap + typebuf.tb_off;
  1874.                     if (*s == RM_SCRIPT
  1875.                         && (mp->m_keys[0] != K_SPECIAL
  1876.                         || mp->m_keys[1] != KS_EXTRA
  1877.                         || mp->m_keys[2]
  1878.                                   != (int)KE_SNR))
  1879.                     continue;
  1880.                     /*
  1881.                      * If one of the typed keys cannot be
  1882.                      * remapped, skip the entry.
  1883.                      */
  1884.                     for (n = mlen; --n >= 0; )
  1885.                     if (*s++ == RM_NONE)
  1886.                         break;
  1887.                     if (n >= 0)
  1888.                     continue;
  1889.  
  1890.                     if (keylen > typebuf.tb_len)
  1891.                     {
  1892.                     if (!timedout)
  1893.                     {
  1894.                         /* break at a partly match */
  1895.                         keylen = KL_PART_MAP;
  1896.                         break;
  1897.                     }
  1898.                     }
  1899.                     else if (keylen > mp_match_len)
  1900.                     {
  1901.                     /* found a longer match */
  1902.                     mp_match = mp;
  1903.                     mp_match_len = keylen;
  1904.                     }
  1905.                 }
  1906.                 else
  1907.                     /* No match; may have to check for
  1908.                      * termcode at next character. */
  1909.                     if (max_mlen < mlen)
  1910.                     max_mlen = mlen;
  1911.                 }
  1912.             }
  1913.  
  1914.             /* If no partly match found, use the longest full
  1915.              * match. */
  1916.             if (keylen != KL_PART_MAP)
  1917.             {
  1918.                 mp = mp_match;
  1919.                 keylen = mp_match_len;
  1920.             }
  1921.             }
  1922.  
  1923.             /* Check for match with 'pastetoggle' */
  1924.             if (*p_pt != NUL && mp == NULL && (State & (INSERT|NORMAL)))
  1925.             {
  1926.             for (mlen = 0; mlen < typebuf.tb_len && p_pt[mlen];
  1927.                                        ++mlen)
  1928.                 if (p_pt[mlen] != typebuf.tb_buf[typebuf.tb_off
  1929.                                       + mlen])
  1930.                     break;
  1931.             if (p_pt[mlen] == NUL)    /* match */
  1932.             {
  1933.                 /* write chars to script file(s) */
  1934.                 if (mlen > typebuf.tb_maplen)
  1935.                 gotchars(typebuf.tb_buf + typebuf.tb_off
  1936.                               + typebuf.tb_maplen,
  1937.                             mlen - typebuf.tb_maplen);
  1938.  
  1939.                 del_typebuf(mlen, 0); /* remove the chars */
  1940.                 set_option_value((char_u *)"paste",
  1941.                              (long)!p_paste, NULL, 0);
  1942.                 if (!(State & INSERT))
  1943.                 {
  1944.                 msg_col = 0;
  1945.                 msg_row = Rows - 1;
  1946.                 msg_clr_eos();        /* clear ruler */
  1947.                 }
  1948.                 showmode();
  1949.                 setcursor();
  1950.                 continue;
  1951.             }
  1952.             /* Need more chars for partly match. */
  1953.             if (mlen == typebuf.tb_len)
  1954.                 keylen = KL_PART_MAP;
  1955.             else if (max_mlen < mlen)
  1956.                 /* no match, may have to check for termcode at
  1957.                  * next character */
  1958.                 max_mlen = mlen + 1;
  1959.             }
  1960.  
  1961.             if ((mp == NULL || max_mlen >= mp_match_len)
  1962.                              && keylen != KL_PART_MAP)
  1963.             {
  1964.             /*
  1965.              * When no matching mapping found or found a
  1966.              * non-matching mapping that matches at least what the
  1967.              * matching mapping matched:
  1968.              * Check if we have a terminal code, when:
  1969.              *  mapping is allowed,
  1970.              *  keys have not been mapped,
  1971.              *  and not an ESC sequence, not in insert mode or
  1972.              *    p_ek is on,
  1973.              *  and when not timed out,
  1974.              */
  1975.             if ((no_mapping == 0 || allow_keys != 0)
  1976.                 && (typebuf.tb_maplen == 0
  1977.                     || (p_remap && typebuf.tb_noremap[
  1978.                            typebuf.tb_off] == RM_YES))
  1979.                 && !timedout)
  1980.             {
  1981.                 keylen = check_termcode(max_mlen + 1, NULL, 0);
  1982.  
  1983.                 /*
  1984.                  * When getting a partial match, but the last
  1985.                  * characters were not typed, don't wait for a
  1986.                  * typed character to complete the termcode.
  1987.                  * This helps a lot when a ":normal" command ends
  1988.                  * in an ESC.
  1989.                  */
  1990.                 if (keylen < 0
  1991.                        && typebuf.tb_len == typebuf.tb_maplen)
  1992.                 keylen = 0;
  1993.             }
  1994.             else
  1995.                 keylen = 0;
  1996.             if (keylen == 0)    /* no matching terminal code */
  1997.             {
  1998. #ifdef AMIGA            /* check for window bounds report */
  1999.                 if (typebuf.tb_maplen == 0 && (typebuf.tb_buf[
  2000.                            typebuf.tb_off] & 0xff) == CSI)
  2001.                 {
  2002.                 for (s = typebuf.tb_buf + typebuf.tb_off + 1;
  2003.                     s < typebuf.tb_buf + typebuf.tb_off
  2004.                                   + typebuf.tb_len
  2005.                    && (isdigit(*s) || *s == ';' || *s == ' ');
  2006.                     ++s)
  2007.                     ;
  2008.                 if (*s == 'r' || *s == '|') /* found one */
  2009.                 {
  2010.                     del_typebuf((int)(s + 1 -
  2011.                        (typebuf.tb_buf + typebuf.tb_off)), 0);
  2012.                     /* get size and redraw screen */
  2013.                     shell_resized();
  2014.                     continue;
  2015.                 }
  2016.                 if (*s == NUL)        /* need more characters */
  2017.                     keylen = KL_PART_KEY;
  2018.                 }
  2019.                 if (keylen >= 0)
  2020. #endif
  2021.                   /* When there was a matching mapping and no
  2022.                    * termcode could be replaced after another one,
  2023.                    * use that mapping. */
  2024.                   if (mp == NULL)
  2025.                   {
  2026. /*
  2027.  * get a character: 2. from the typeahead buffer
  2028.  */
  2029.                 c = typebuf.tb_buf[typebuf.tb_off] & 255;
  2030.                 if (advance)    /* remove chars from tb_buf */
  2031.                 {
  2032.                     cmd_silent = (typebuf.tb_silent > 0);
  2033.                     if (typebuf.tb_maplen > 0)
  2034.                     KeyTyped = FALSE;
  2035.                     else
  2036.                     {
  2037.                     KeyTyped = TRUE;
  2038.                     /* write char to script file(s) */
  2039.                     gotchars(typebuf.tb_buf
  2040.                              + typebuf.tb_off, 1);
  2041.                     }
  2042.                     del_typebuf(1, 0);
  2043.                 }
  2044.                 break;        /* got character, break for loop */
  2045.                   }
  2046.             }
  2047.             if (keylen > 0)        /* full matching terminal code */
  2048.             {
  2049. #if defined(FEAT_GUI) && defined(FEAT_MENU)
  2050.                 if (typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL
  2051.                      && typebuf.tb_buf[typebuf.tb_off + 1]
  2052.                                    == KS_MENU)
  2053.                 {
  2054.                 /*
  2055.                  * Using a menu may cause a break in undo!
  2056.                  * It's like using gotchars(), but without
  2057.                  * recording or writing to a script file.
  2058.                  */
  2059.                 may_sync_undo();
  2060.                 del_typebuf(3, 0);
  2061.                 idx = get_menu_index(current_menu, local_State);
  2062.                 if (idx != MENU_INDEX_INVALID)
  2063.                 {
  2064. # ifdef FEAT_VISUAL
  2065.                     /*
  2066.                      * In Select mode, a Visual mode menu is
  2067.                      * used.  Switch to Visual mode
  2068.                      * temporarily.  Append K_SELECT to switch
  2069.                      * back to Select mode.
  2070.                      */
  2071.                     if (VIsual_active && VIsual_select)
  2072.                     {
  2073.                     VIsual_select = FALSE;
  2074.                     (void)ins_typebuf(K_SELECT_STRING,
  2075.                           REMAP_NONE, 0, TRUE, FALSE);
  2076.                     }
  2077. # endif
  2078.                     ins_typebuf(current_menu->strings[idx],
  2079.                         current_menu->noremap[idx],
  2080.                         0, TRUE,
  2081.                            current_menu->silent[idx]);
  2082.                 }
  2083.                 }
  2084. #endif /* FEAT_GUI */
  2085.                 continue;    /* try mapping again */
  2086.             }
  2087.  
  2088.             /* Partial match: get some more characters.  When a
  2089.              * matching mapping was found use that one. */
  2090.             if (mp == NULL || keylen < 0)
  2091.                 keylen = KL_PART_KEY;
  2092.             else
  2093.                 keylen = mp_match_len;
  2094.             }
  2095.  
  2096.             /* complete match */
  2097.             if (keylen >= 0 && keylen <= typebuf.tb_len)
  2098.             {
  2099.             /* write chars to script file(s) */
  2100.             if (keylen > typebuf.tb_maplen)
  2101.                 gotchars(typebuf.tb_buf + typebuf.tb_off
  2102.                               + typebuf.tb_maplen,
  2103.                           keylen - typebuf.tb_maplen);
  2104.  
  2105.             cmd_silent = (typebuf.tb_silent > 0);
  2106.             del_typebuf(keylen, 0);    /* remove the mapped keys */
  2107.  
  2108.             /*
  2109.              * Put the replacement string in front of mapstr.
  2110.              * The depth check catches ":map x y" and ":map y x".
  2111.              */
  2112.             if (++mapdepth >= p_mmd)
  2113.             {
  2114.                 EMSG(_("E223: recursive mapping"));
  2115.                 if (State & CMDLINE)
  2116.                 redrawcmdline();
  2117.                 else
  2118.                 setcursor();
  2119.                 flush_buffers(FALSE);
  2120.                 mapdepth = 0;    /* for next one */
  2121.                 c = -1;
  2122.                 break;
  2123.             }
  2124.  
  2125. #ifdef FEAT_VISUAL
  2126.             /*
  2127.              * In Select mode, a Visual mode mapping is used.
  2128.              * Switch to Visual mode temporarily.  Append K_SELECT
  2129.              * to switch back to Select mode.
  2130.              */
  2131.             if (VIsual_active && VIsual_select)
  2132.             {
  2133.                 VIsual_select = FALSE;
  2134.                 (void)ins_typebuf(K_SELECT_STRING, REMAP_NONE,
  2135.                                   0, TRUE, FALSE);
  2136.             }
  2137. #endif
  2138.  
  2139.             /*
  2140.              * Insert the 'to' part in the typebuf.tb_buf.
  2141.              * If 'from' field is the same as the start of the
  2142.              * 'to' field, don't remap the first character.
  2143.              * If m_noremap is set, don't remap the whole 'to'
  2144.              * part.
  2145.              */
  2146.             if (ins_typebuf(mp->m_str,
  2147.                 mp->m_noremap != REMAP_YES
  2148.                         ? mp->m_noremap
  2149.                         : STRNCMP(mp->m_str, mp->m_keys,
  2150.                                    (size_t)keylen)
  2151.                                   ? REMAP_YES : 1,
  2152.                 0, TRUE, cmd_silent || mp->m_silent) == FAIL)
  2153.             {
  2154.                 c = -1;
  2155.                 break;
  2156.             }
  2157.             continue;
  2158.             }
  2159.         }
  2160.  
  2161. /*
  2162.  * get a character: 3. from the user - handle <Esc> in Insert mode
  2163.  */
  2164.         /*
  2165.          * special case: if we get an <ESC> in insert mode and there
  2166.          * are no more characters at once, we pretend to go out of
  2167.          * insert mode.  This prevents the one second delay after
  2168.          * typing an <ESC>.  If we get something after all, we may
  2169.          * have to redisplay the mode. That the cursor is in the wrong
  2170.          * place does not matter.
  2171.          */
  2172.         c = 0;
  2173. #ifdef FEAT_CMDL_INFO
  2174.         new_wcol = curwin->w_wcol;
  2175.         new_wrow = curwin->w_wrow;
  2176. #endif
  2177.         if (       advance
  2178.             && typebuf.tb_len == 1
  2179.             && typebuf.tb_buf[typebuf.tb_off] == ESC
  2180.             && !no_mapping
  2181. #ifdef FEAT_EX_EXTRA
  2182.             && ex_normal_busy == 0
  2183. #endif
  2184.             && typebuf.tb_maplen == 0
  2185.             && (State & INSERT)
  2186.             && (p_timeout || (keylen == KL_PART_KEY && p_ttimeout))
  2187.             && (c = inchar(typebuf.tb_buf + typebuf.tb_off
  2188.                             + typebuf.tb_len, 3, 25L))
  2189.                                      == 0)
  2190.         {
  2191.             colnr_T    col = 0, vcol;
  2192.             char_u    *ptr;
  2193.  
  2194.             if (p_smd)
  2195.             {
  2196.             unshowmode(TRUE);
  2197.             mode_deleted = TRUE;
  2198.             }
  2199. #ifdef FEAT_GUI
  2200.             /* may show different cursor shape */
  2201.             if (gui.in_use)
  2202.             {
  2203.             int        save_State;
  2204.  
  2205.             save_State = State;
  2206.             State = NORMAL;
  2207.             gui_update_cursor(TRUE, FALSE);
  2208.             State = save_State;
  2209.             shape_changed = TRUE;
  2210.             }
  2211. #endif
  2212.             validate_cursor();
  2213.             old_wcol = curwin->w_wcol;
  2214.             old_wrow = curwin->w_wrow;
  2215.  
  2216.             /* move cursor left, if possible */
  2217.             if (curwin->w_cursor.col != 0)
  2218.             {
  2219.             if (curwin->w_wcol > 0)
  2220.             {
  2221.                 if (did_ai)
  2222.                 {
  2223.                 /*
  2224.                  * We are expecting to truncate the trailing
  2225.                  * white-space, so find the last non-white
  2226.                  * character -- webb
  2227.                  */
  2228.                 col = vcol = curwin->w_wcol = 0;
  2229.                 ptr = ml_get_curline();
  2230.                 while (col < curwin->w_cursor.col)
  2231.                 {
  2232.                     if (!vim_iswhite(ptr[col]))
  2233.                     curwin->w_wcol = vcol;
  2234.                     vcol += lbr_chartabsize(ptr + col,
  2235.                                    (colnr_T)vcol);
  2236. #ifdef FEAT_MBYTE
  2237.                     if (has_mbyte)
  2238.                     col += (*mb_ptr2len_check)(ptr + col);
  2239.                     else
  2240. #endif
  2241.                     ++col;
  2242.                 }
  2243.                 curwin->w_wrow = curwin->w_cline_row
  2244.                        + curwin->w_wcol / W_WIDTH(curwin);
  2245.                 curwin->w_wcol %= W_WIDTH(curwin);
  2246.                 curwin->w_wcol += curwin_col_off();
  2247. #ifdef FEAT_MBYTE
  2248.                 col = 0;    /* no correction needed */
  2249. #endif
  2250.                 }
  2251.                 else
  2252.                 {
  2253.                 --curwin->w_wcol;
  2254. #ifdef FEAT_MBYTE
  2255.                 col = curwin->w_cursor.col - 1;
  2256. #endif
  2257.                 }
  2258.             }
  2259.             else if (curwin->w_p_wrap && curwin->w_wrow)
  2260.             {
  2261.                 --curwin->w_wrow;
  2262.                 curwin->w_wcol = W_WIDTH(curwin) - 1;
  2263. #ifdef FEAT_MBYTE
  2264.                 col = curwin->w_cursor.col - 1;
  2265. #endif
  2266.             }
  2267. #ifdef FEAT_MBYTE
  2268.             if (has_mbyte && col > 0 && curwin->w_wcol > 0)
  2269.             {
  2270.                 /* Correct when the cursor is on the right halve
  2271.                  * of a double-wide character. */
  2272.                 ptr = ml_get_curline();
  2273.                 col -= (*mb_head_off)(ptr, ptr + col);
  2274.                 if ((*mb_ptr2cells)(ptr + col) > 1)
  2275.                 --curwin->w_wcol;
  2276.             }
  2277. #endif
  2278.             }
  2279.             setcursor();
  2280.             out_flush();
  2281. #ifdef FEAT_CMDL_INFO
  2282.             new_wcol = curwin->w_wcol;
  2283.             new_wrow = curwin->w_wrow;
  2284. #endif
  2285.             curwin->w_wcol = old_wcol;
  2286.             curwin->w_wrow = old_wrow;
  2287.         }
  2288.         if (c < 0)
  2289.             continue;    /* end of input script reached */
  2290.         typebuf.tb_len += c;
  2291.  
  2292.         /* buffer full, don't map */
  2293.         if (typebuf.tb_len >= typebuf.tb_maplen + MAXMAPLEN)
  2294.         {
  2295.             timedout = TRUE;
  2296.             continue;
  2297.         }
  2298.  
  2299. #ifdef FEAT_EX_EXTRA
  2300.         if (ex_normal_busy > 0)
  2301.         {
  2302. # ifdef FEAT_CMDWIN
  2303.             static int tc = 0;
  2304. # endif
  2305.  
  2306.             /* No typeahead left and inside ":normal".  Must return
  2307.              * something to avoid getting stuck.  When an incomplete
  2308.              * mapping is present, behave like it timed out. */
  2309.             if (typebuf.tb_len > 0)
  2310.             {
  2311.             timedout = TRUE;
  2312.             continue;
  2313.             }
  2314.             /* When 'insertmode' is set, ESC just beeps in Insert
  2315.              * mode.  Use CTRL-L to make edit() return.
  2316.              * For the command line only CTRL-C always breaks it.
  2317.              * For the cmdline window: Alternate between ESC and
  2318.              * CTRL-C: ESC for most situations and CTRL-C to close the
  2319.              * cmdline window. */
  2320.             if (p_im && (State & INSERT))
  2321.             c = Ctrl_L;
  2322.             else if ((State & CMDLINE)
  2323. # ifdef FEAT_CMDWIN
  2324.                 || (cmdwin_type > 0 && tc == ESC)
  2325. # endif
  2326.                 )
  2327.             c = Ctrl_C;
  2328.             else
  2329.             c = ESC;
  2330. # ifdef FEAT_CMDWIN
  2331.             tc = c;
  2332. # endif
  2333.             break;
  2334.         }
  2335. #endif
  2336.  
  2337. /*
  2338.  * get a character: 3. from the user - update display
  2339.  */
  2340.         /* In insert mode a screen update is skipped when characters
  2341.          * are still available.  But when those available characters
  2342.          * are part of a mapping, and we are going to do a blocking
  2343.          * wait here.  Need to update the screen to display the
  2344.          * changed text so far. */
  2345.         if ((State & INSERT) && advance && must_redraw != 0)
  2346.         {
  2347.             update_screen(0);
  2348.             setcursor(); /* put cursor back where it belongs */
  2349.         }
  2350.  
  2351.         /*
  2352.          * If we have a partial match (and are going to wait for more
  2353.          * input from the user), show the partially matched characters
  2354.          * to the user with showcmd.
  2355.          */
  2356. #ifdef FEAT_CMDL_INFO
  2357.         i = 0;
  2358. #endif
  2359.         c1 = 0;
  2360.         if (typebuf.tb_len > 0 && advance && !exmode_active)
  2361.         {
  2362.             if (((State & (NORMAL | INSERT)) || State == LANGMAP)
  2363.                 && State != HITRETURN)
  2364.             {
  2365.             /* this looks nice when typing a dead character map */
  2366.             if (State & INSERT
  2367.                 && ptr2cells(typebuf.tb_buf + typebuf.tb_off
  2368.                            + typebuf.tb_len - 1) == 1)
  2369.             {
  2370.                 edit_putchar(typebuf.tb_buf[typebuf.tb_off
  2371.                         + typebuf.tb_len - 1], FALSE);
  2372.                 setcursor(); /* put cursor back where it belongs */
  2373.                 c1 = 1;
  2374.             }
  2375. #ifdef FEAT_CMDL_INFO
  2376.             /* need to use the col and row from above here */
  2377.             old_wcol = curwin->w_wcol;
  2378.             old_wrow = curwin->w_wrow;
  2379.             curwin->w_wcol = new_wcol;
  2380.             curwin->w_wrow = new_wrow;
  2381.             push_showcmd();
  2382.             if (typebuf.tb_len > SHOWCMD_COLS)
  2383.                 i = typebuf.tb_len - SHOWCMD_COLS;
  2384.             while (i < typebuf.tb_len)
  2385.                 (void)add_to_showcmd(typebuf.tb_buf[typebuf.tb_off
  2386.                                       + i++]);
  2387.             curwin->w_wcol = old_wcol;
  2388.             curwin->w_wrow = old_wrow;
  2389. #endif
  2390.             }
  2391.  
  2392.             /* this looks nice when typing a dead character map */
  2393.             if ((State & CMDLINE)
  2394.                 && ptr2cells(typebuf.tb_buf + typebuf.tb_off
  2395.                            + typebuf.tb_len - 1) == 1)
  2396.             {
  2397.             putcmdline(typebuf.tb_buf[typebuf.tb_off
  2398.                         + typebuf.tb_len - 1], FALSE);
  2399.             c1 = 1;
  2400.             }
  2401.         }
  2402.  
  2403. /*
  2404.  * get a character: 3. from the user - get it
  2405.  */
  2406.         c = inchar(typebuf.tb_buf + typebuf.tb_off + typebuf.tb_len,
  2407.             typebuf.tb_buflen - typebuf.tb_off - typebuf.tb_len - 1,
  2408.             !advance
  2409.                 ? 0
  2410.                 : ((typebuf.tb_len == 0
  2411.                     || !(p_timeout || (p_ttimeout
  2412.                            && keylen == KL_PART_KEY)))
  2413.                     ? -1L
  2414.                     : ((keylen == KL_PART_KEY && p_ttm >= 0)
  2415.                         ? p_ttm
  2416.                         : p_tm)));
  2417.  
  2418. #ifdef FEAT_CMDL_INFO
  2419.         if (i != 0)
  2420.             pop_showcmd();
  2421. #endif
  2422.         if (c1 == 1)
  2423.         {
  2424.             if (State & INSERT)
  2425.             edit_unputchar();
  2426.             if (State & CMDLINE)
  2427.             unputcmdline();
  2428.             setcursor();    /* put cursor back where it belongs */
  2429.         }
  2430.  
  2431.         if (c < 0)
  2432.             continue;        /* end of input script reached */
  2433.         if (c == NUL)        /* no character available */
  2434.         {
  2435.             if (!advance)
  2436.             break;
  2437.             if (typebuf.tb_len > 0)    /* timed out */
  2438.             {
  2439.             timedout = TRUE;
  2440.             continue;
  2441.             }
  2442.         }
  2443.         else
  2444.         {        /* allow mapping for just typed characters */
  2445.             while (typebuf.tb_buf[typebuf.tb_off
  2446.                              + typebuf.tb_len] != NUL)
  2447.             typebuf.tb_noremap[typebuf.tb_off
  2448.                          + typebuf.tb_len++] = RM_YES;
  2449. #ifdef USE_IM_CONTROL
  2450.             /* Get IM status right after getting keys, not after the
  2451.              * timeout for a mapping (focus may be lost by then). */
  2452.             vgetc_im_active = im_get_status();
  2453. #endif
  2454.         }
  2455.         }        /* for (;;) */
  2456.     }    /* if (!character from stuffbuf) */
  2457.  
  2458.             /* if advance is FALSE don't loop on NULs */
  2459.     } while (c < 0 || (advance && c == NUL));
  2460.  
  2461.     /*
  2462.      * The "INSERT" message is taken care of here:
  2463.      *     if we return an ESC to exit insert mode, the message is deleted
  2464.      *     if we don't return an ESC but deleted the message before, redisplay it
  2465.      */
  2466.     if (advance && p_smd && (State & INSERT))
  2467.     {
  2468.     if (c == ESC && !mode_deleted && !no_mapping)
  2469.     {
  2470.         if (typebuf.tb_len && !KeyTyped)
  2471.         redraw_cmdline = TRUE;        /* delete mode later */
  2472.         else
  2473.         unshowmode(FALSE);
  2474.     }
  2475.     else if (c != ESC && mode_deleted)
  2476.     {
  2477.         if (typebuf.tb_len && !KeyTyped)
  2478.         redraw_cmdline = TRUE;        /* show mode later */
  2479.         else
  2480.         showmode();
  2481.     }
  2482.     }
  2483. #ifdef FEAT_GUI
  2484.     /* may unshow different cursor shape */
  2485.     if (gui.in_use && shape_changed)
  2486.     gui_update_cursor(TRUE, FALSE);
  2487. #endif
  2488.  
  2489.     vgetc_busy = FALSE;
  2490.  
  2491.     return c;
  2492. }
  2493.  
  2494. /*
  2495.  * inchar() - get one character from
  2496.  *    1. a scriptfile
  2497.  *    2. the keyboard
  2498.  *
  2499.  *  As much characters as we can get (upto 'maxlen') are put in buf and
  2500.  *  NUL terminated (buffer length must be 'maxlen' + 1).
  2501.  *  Minimum for 'maxlen' is 3!!!!
  2502.  *
  2503.  *  If we got an interrupt all input is read until none is available.
  2504.  *
  2505.  *  If wait_time == 0  there is no waiting for the char.
  2506.  *  If wait_time == n  we wait for n msec for a character to arrive.
  2507.  *  If wait_time == -1 we wait forever for a character to arrive.
  2508.  *
  2509.  *  Return the number of obtained characters.
  2510.  *  Return -1 when end of input script reached.
  2511.  */
  2512.  
  2513.     int
  2514. inchar(buf, maxlen, wait_time)
  2515.     char_u    *buf;
  2516.     int        maxlen;
  2517.     long    wait_time;        /* milli seconds */
  2518. {
  2519.     int        len = 0;        /* init for GCC */
  2520.     int        retesc = FALSE;        /* return ESC with gotint */
  2521.     int        script_char;
  2522.  
  2523.     if (wait_time == -1L || wait_time > 100L)  /* flush output before waiting */
  2524.     {
  2525.     cursor_on();
  2526.     out_flush();
  2527. #ifdef FEAT_GUI
  2528.     if (gui.in_use)
  2529.     {
  2530.         gui_update_cursor(FALSE, FALSE);
  2531. # ifdef FEAT_MOUSESHAPE
  2532.         if (postponed_mouseshape)
  2533.         update_mouseshape(-1);
  2534. # endif
  2535.     }
  2536. #endif
  2537.     }
  2538.  
  2539.     /*
  2540.      * Don't reset these when at the hit-return prompt, otherwise a endless
  2541.      * recursive loop may result (write error in swapfile, hit-return, timeout
  2542.      * on char wait, flush swapfile, write error....).
  2543.      */
  2544.     if (State != HITRETURN)
  2545.     {
  2546.     did_outofmem_msg = FALSE;   /* display out of memory message (again) */
  2547.     did_swapwrite_msg = FALSE;  /* display swap file write error again */
  2548.     }
  2549.     undo_off = FALSE;            /* restart undo now */
  2550.  
  2551.     /*
  2552.      * first try script file
  2553.      *    If interrupted: Stop reading script files.
  2554.      */
  2555.     script_char = -1;
  2556.     while (scriptin[curscript] != NULL && script_char < 0)
  2557.     {
  2558.     if (got_int || (script_char = getc(scriptin[curscript])) < 0)
  2559.     {
  2560.         /* Reached EOF.
  2561.          * Careful: closescript() frees typebuf.tb_buf[] and buf[] may
  2562.          * point inside typebuf.tb_buf[].  Don't use buf[] after this! */
  2563.         closescript();
  2564.         /*
  2565.          * When reading script file is interrupted, return an ESC to get
  2566.          * back to normal mode.
  2567.          * Otherwise return -1, because typebuf.tb_buf[] has changed.
  2568.          */
  2569.         if (got_int)
  2570.         retesc = TRUE;
  2571.         else
  2572.         return -1;
  2573.     }
  2574.     else
  2575.     {
  2576.         buf[0] = script_char;
  2577.         len = 1;
  2578.     }
  2579.     }
  2580.  
  2581.     if (script_char < 0)    /* did not get a character from script */
  2582.     {
  2583.     /*
  2584.      * If we got an interrupt, skip all previously typed characters and
  2585.      * return TRUE if quit reading script file.
  2586.      * Don't use buf[] here, closescript() may have freed typebuf.tb_buf[]
  2587.      * and buf may be pointing inside typebuf.tb_buf[].
  2588.      */
  2589.     if (got_int)
  2590.     {
  2591. #define DUM_LEN MAXMAPLEN * 3 + 3
  2592.         char_u    dum[DUM_LEN + 1];
  2593.  
  2594.         while (ui_inchar(dum, DUM_LEN, 0L) != 0)
  2595.         ;
  2596.         return retesc;
  2597.     }
  2598.  
  2599.     /*
  2600.      * Always flush the output characters when getting input characters
  2601.      * from the user.
  2602.      */
  2603.     out_flush();
  2604.  
  2605.     /*
  2606.      * fill up to a third of the buffer, because each character may be
  2607.      * tripled below
  2608.      */
  2609.     len = ui_inchar(buf, maxlen / 3, wait_time);
  2610.     }
  2611.  
  2612.     return fix_input_buffer(buf, len, script_char >= 0);
  2613. }
  2614.  
  2615. /*
  2616.  * Fix typed characters for use by vgetc() and check_termcode().
  2617.  * buf[] must have room to triple the number of bytes!
  2618.  * Returns the new length.
  2619.  */
  2620.     int
  2621. fix_input_buffer(buf, len, script)
  2622.     char_u    *buf;
  2623.     int        len;
  2624.     int        script;        /* TRUE when reading from a script */
  2625. {
  2626.     int        i;
  2627.     char_u    *p = buf;
  2628.  
  2629.     /*
  2630.      * Two characters are special: NUL and K_SPECIAL.
  2631.      * When compiled With the GUI CSI is also special.
  2632.      * Replace         NUL by K_SPECIAL KS_ZERO     KE_FILLER
  2633.      * Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER
  2634.      * Replace       CSI by K_SPECIAL KS_EXTRA   KE_CSI
  2635.      * Don't replace K_SPECIAL when reading a script file.
  2636.      */
  2637.     for (i = len; --i >= 0; ++p)
  2638.     {
  2639. #ifdef FEAT_GUI
  2640.     /* When the GUI is used any character can come after a CSI, don't
  2641.      * escape it. */
  2642.     if (gui.in_use && p[0] == CSI && i >= 2)
  2643.     {
  2644.         p += 2;
  2645.         i -= 2;
  2646.     }
  2647.     /* When the GUI is not used CSI needs to be escaped. */
  2648.     else if (!gui.in_use && p[0] == CSI)
  2649.     {
  2650.         mch_memmove(p + 3, p + 1, (size_t)i);
  2651.         *p++ = K_SPECIAL;
  2652.         *p++ = KS_EXTRA;
  2653.         *p = (int)KE_CSI;
  2654.         len += 2;
  2655.     }
  2656.     else
  2657. #endif
  2658.     if (p[0] == NUL || (p[0] == K_SPECIAL && !script))
  2659.     {
  2660.         mch_memmove(p + 3, p + 1, (size_t)i);
  2661.         p[2] = K_THIRD(p[0]);
  2662.         p[1] = K_SECOND(p[0]);
  2663.         p[0] = K_SPECIAL;
  2664.         p += 2;
  2665.         len += 2;
  2666.     }
  2667.     }
  2668.     *p = NUL;        /* add trailing NUL */
  2669.     return len;
  2670. }
  2671.  
  2672. /*
  2673.  * map[!]            : show all key mappings
  2674.  * map[!] {lhs}            : show key mapping for {lhs}
  2675.  * map[!] {lhs} {rhs}        : set key mapping for {lhs} to {rhs}
  2676.  * noremap[!] {lhs} {rhs}   : same, but no remapping for {rhs}
  2677.  * unmap[!] {lhs}        : remove key mapping for {lhs}
  2678.  * abbr                : show all abbreviations
  2679.  * abbr {lhs}            : show abbreviations for {lhs}
  2680.  * abbr {lhs} {rhs}        : set abbreviation for {lhs} to {rhs}
  2681.  * noreabbr {lhs} {rhs}        : same, but no remapping for {rhs}
  2682.  * unabbr {lhs}            : remove abbreviation for {lhs}
  2683.  *
  2684.  * maptype: 0 for :map, 1 for :unmap, 2 for noremap.
  2685.  *
  2686.  * arg is pointer to any arguments. Note: arg cannot be a read-only string,
  2687.  * it will be modified.
  2688.  *
  2689.  * for :map   mode is NORMAL + VISUAL + OP_PENDING
  2690.  * for :map!  mode is INSERT + CMDLINE
  2691.  * for :cmap  mode is CMDLINE
  2692.  * for :imap  mode is INSERT
  2693.  * for :lmap  mode is LANGMAP
  2694.  * for :nmap  mode is NORMAL
  2695.  * for :vmap  mode is VISUAL
  2696.  * for :omap  mode is OP_PENDING
  2697.  *
  2698.  * for :abbr  mode is INSERT + CMDLINE
  2699.  * for :iabbr mode is INSERT
  2700.  * for :cabbr mode is CMDLINE
  2701.  *
  2702.  * Return 0 for success
  2703.  *      1 for invalid arguments
  2704.  *      2 for no match
  2705.  *      4 for out of mem
  2706.  *      5 for entry not unique
  2707.  */
  2708.     int
  2709. do_map(maptype, arg, mode, abbrev)
  2710.     int        maptype;
  2711.     char_u    *arg;
  2712.     int        mode;
  2713.     int        abbrev;        /* not a mapping but an abbreviation */
  2714. {
  2715.     char_u    *keys;
  2716.     mapblock_T    *mp, **mpp;
  2717.     char_u    *rhs;
  2718.     char_u    *p;
  2719.     int        n;
  2720.     int        len = 0;    /* init for GCC */
  2721.     char_u    *newstr;
  2722.     int        hasarg;
  2723.     int        haskey;
  2724.     int        did_it = FALSE;
  2725. #ifdef FEAT_LOCALMAP
  2726.     int        did_local = FALSE;
  2727. #endif
  2728.     int        round;
  2729.     char_u    *keys_buf = NULL;
  2730.     char_u    *arg_buf = NULL;
  2731.     int        retval = 0;
  2732.     int        do_backslash;
  2733.     int        hash;
  2734.     int        new_hash;
  2735.     mapblock_T    **abbr_table;
  2736.     mapblock_T    **map_table;
  2737.     int        unique = FALSE;
  2738.     int        silent = FALSE;
  2739.     int        noremap;
  2740.  
  2741.     keys = arg;
  2742.     map_table = maphash;
  2743.     abbr_table = &first_abbr;
  2744.  
  2745.     /* For ":noremap" don't remap, otherwise do remap. */
  2746.     if (maptype == 2)
  2747.     noremap = REMAP_NONE;
  2748.     else
  2749.     noremap = REMAP_YES;
  2750.  
  2751.     /* Accept <buffer>, <script> and <unique> in any order. */
  2752.     for (;;)
  2753.     {
  2754. #ifdef FEAT_LOCALMAP
  2755.     /*
  2756.      * Check for "<buffer>": mapping local to buffer.
  2757.      */
  2758.     if (STRNCMP(keys, "<buffer>", 8) == 0)
  2759.     {
  2760.         keys = skipwhite(keys + 8);
  2761.         map_table = curbuf->b_maphash;
  2762.         abbr_table = &curbuf->b_first_abbr;
  2763.         continue;
  2764.     }
  2765. #endif
  2766.  
  2767.     /*
  2768.      * Check for "<silent>": don't echo commands.
  2769.      */
  2770.     if (STRNCMP(keys, "<silent>", 8) == 0)
  2771.     {
  2772.         keys = skipwhite(keys + 8);
  2773.         silent = TRUE;
  2774.         continue;
  2775.     }
  2776.  
  2777. #ifdef FEAT_EVAL
  2778.     /*
  2779.      * Check for "<script>": remap script-local mappings only
  2780.      */
  2781.     if (STRNCMP(keys, "<script>", 8) == 0)
  2782.     {
  2783.         keys = skipwhite(keys + 8);
  2784.         noremap = REMAP_SCRIPT;
  2785.         continue;
  2786.     }
  2787. #endif
  2788.     /*
  2789.      * Check for "<unique>": don't overwrite an existing mapping.
  2790.      */
  2791.     if (STRNCMP(keys, "<unique>", 8) == 0)
  2792.     {
  2793.         keys = skipwhite(keys + 8);
  2794.         unique = TRUE;
  2795.         continue;
  2796.     }
  2797.     break;
  2798.     }
  2799.  
  2800.     validate_maphash();
  2801.  
  2802.     /*
  2803.      * find end of keys and skip CTRL-Vs (and backslashes) in it
  2804.      * Accept backslash like CTRL-V when 'cpoptions' does not contain 'B'.
  2805.      * with :unmap white space is included in the keys, no argument possible
  2806.      */
  2807.     p = keys;
  2808.     do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
  2809.     while (*p && (maptype == 1 || !vim_iswhite(*p)))
  2810.     {
  2811.     if ((p[0] == Ctrl_V || (do_backslash && p[0] == '\\')) &&
  2812.                                   p[1] != NUL)
  2813.         ++p;        /* skip CTRL-V or backslash */
  2814.     ++p;
  2815.     }
  2816.     if (*p != NUL)
  2817.     *p++ = NUL;
  2818.     p = skipwhite(p);
  2819.     rhs = p;
  2820.     hasarg = (*rhs != NUL);
  2821.     haskey = (*keys != NUL);
  2822.  
  2823.     /* check for :unmap without argument */
  2824.     if (maptype == 1 && !haskey)
  2825.     {
  2826.     retval = 1;
  2827.     goto theend;
  2828.     }
  2829.  
  2830.     /*
  2831.      * If mapping has been given as ^V<C_UP> say, then replace the term codes
  2832.      * with the appropriate two bytes. If it is a shifted special key, unshift
  2833.      * it too, giving another two bytes.
  2834.      * replace_termcodes() may move the result to allocated memory, which
  2835.      * needs to be freed later (*keys_buf and *arg_buf).
  2836.      * replace_termcodes() also removes CTRL-Vs and sometimes backslashes.
  2837.      */
  2838.     if (haskey)
  2839.     keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE);
  2840.     if (hasarg)
  2841.     {
  2842.     if (STRICMP(rhs, "<nop>") == 0)        /* "<Nop>" means nothing */
  2843.         rhs = (char_u *)"";
  2844.     else
  2845.         rhs = replace_termcodes(rhs, &arg_buf, FALSE, TRUE);
  2846.     }
  2847.  
  2848. #ifdef FEAT_FKMAP
  2849.     /*
  2850.      * when in right-to-left mode and alternate keymap option set,
  2851.      * reverse the character flow in the rhs in Farsi.
  2852.      */
  2853.     if (p_altkeymap && curwin->w_p_rl)
  2854.     lrswap(rhs);
  2855. #endif
  2856.  
  2857.     /*
  2858.      * check arguments and translate function keys
  2859.      */
  2860.     if (haskey)
  2861.     {
  2862.     len = (int)STRLEN(keys);
  2863.     if (len > MAXMAPLEN)        /* maximum length of MAXMAPLEN chars */
  2864.     {
  2865.         retval = 1;
  2866.         goto theend;
  2867.     }
  2868.  
  2869.     if (abbrev && maptype != 1)
  2870.     {
  2871.         /*
  2872.          * If an abbreviation ends in a keyword character, the
  2873.          * rest must be all keyword-char or all non-keyword-char.
  2874.          * Otherwise we won't be able to find the start of it in a
  2875.          * vi-compatible way.
  2876.          */
  2877. #ifdef FEAT_MBYTE
  2878.         if (has_mbyte)
  2879.         {
  2880.         int    first, last;
  2881.         int    same = -1;
  2882.  
  2883.         first = vim_iswordp(keys);
  2884.         last = first;
  2885.         p = keys + mb_ptr2len_check(keys);
  2886.         n = 1;
  2887.         while (p < keys + len)
  2888.         {
  2889.             ++n;            /* nr of (multi-byte) chars */
  2890.             last = vim_iswordp(p);    /* type of last char */
  2891.             if (same == -1 && last != first)
  2892.             same = n - 1;        /* count of same char type */
  2893.             p += mb_ptr2len_check(p);
  2894.         }
  2895.         if (last && n > 2 && same >= 0 && same < n - 1)
  2896.         {
  2897.             retval = 1;
  2898.             goto theend;
  2899.         }
  2900.         }
  2901.         else
  2902. #endif
  2903.         if (vim_iswordc(keys[len - 1]))    /* ends in keyword char */
  2904.             for (n = 0; n < len - 2; ++n)
  2905.             if (vim_iswordc(keys[n]) != vim_iswordc(keys[len - 2]))
  2906.             {
  2907.                 retval = 1;
  2908.                 goto theend;
  2909.             }
  2910.         /* An abbrevation cannot contain white space. */
  2911.         for (n = 0; n < len; ++n)
  2912.         if (vim_iswhite(keys[n]))
  2913.         {
  2914.             retval = 1;
  2915.             goto theend;
  2916.         }
  2917.     }
  2918.     }
  2919.  
  2920.     if (haskey && hasarg && abbrev)    /* if we will add an abbreviation */
  2921.     no_abbr = FALSE;        /* reset flag that indicates there are
  2922.                                 no abbreviations */
  2923.  
  2924.     if (!haskey || (maptype != 1 && !hasarg))
  2925.     msg_start();
  2926.  
  2927.     /* When definding a ":lmap" switch on using them. */
  2928.     if (hasarg && maptype != 1 && mode == LANGMAP)
  2929.     {
  2930.     curbuf->b_p_iminsert = B_IMODE_LMAP;
  2931.     if (curbuf->b_p_imsearch != B_IMODE_USE_INSERT)
  2932.         curbuf->b_p_imsearch = B_IMODE_LMAP;
  2933.     set_iminsert_global();
  2934.     set_imsearch_global();
  2935. #ifdef FEAT_WINDOWS
  2936.     status_redraw_curbuf();
  2937. #endif
  2938.     }
  2939.  
  2940. #ifdef FEAT_LOCALMAP
  2941.     /*
  2942.      * Check if a new local mapping wasn't already defined globally.
  2943.      */
  2944.     if (map_table == curbuf->b_maphash && haskey && hasarg && maptype != 1)
  2945.     {
  2946.     /* need to loop over all global hash lists */
  2947.     for (hash = 0; hash < 256 && !got_int; ++hash)
  2948.     {
  2949.         if (abbrev)
  2950.         {
  2951.         if (hash != 0)    /* there is only one abbreviation list */
  2952.             break;
  2953.         mp = first_abbr;
  2954.         }
  2955.         else
  2956.         mp = maphash[hash];
  2957.         for ( ; mp != NULL && !got_int; mp = mp->m_next)
  2958.         {
  2959.         /* check entries with the same mode */
  2960.         if ((mp->m_mode & mode) != 0
  2961.             && mp->m_keylen == len
  2962.             && unique
  2963.             && STRNCMP(mp->m_keys, keys, (size_t)len) == 0)
  2964.         {
  2965.             if (abbrev)
  2966.             EMSG2(_("E224: global abbreviation already exists for %s"),
  2967.                 mp->m_keys);
  2968.             else
  2969.             EMSG2(_("E225: global mapping already exists for %s"),
  2970.                 mp->m_keys);
  2971.             retval = 5;
  2972.             goto theend;
  2973.         }
  2974.         }
  2975.     }
  2976.     }
  2977.  
  2978.     /*
  2979.      * When listing global mappings, also list buffer-local ones here.
  2980.      */
  2981.     if (map_table != curbuf->b_maphash && !hasarg && maptype != 1)
  2982.     {
  2983.     /* need to loop over all global hash lists */
  2984.     for (hash = 0; hash < 256 && !got_int; ++hash)
  2985.     {
  2986.         if (abbrev)
  2987.         {
  2988.         if (hash != 0)    /* there is only one abbreviation list */
  2989.             break;
  2990.         mp = curbuf->b_first_abbr;
  2991.         }
  2992.         else
  2993.         mp = curbuf->b_maphash[hash];
  2994.         for ( ; mp != NULL && !got_int; mp = mp->m_next)
  2995.         {
  2996.         /* check entries with the same mode */
  2997.         if ((mp->m_mode & mode) != 0)
  2998.         {
  2999.             if (!haskey)            /* show all entries */
  3000.             {
  3001.             showmap(mp, TRUE);
  3002.             did_local = TRUE;
  3003.             }
  3004.             else
  3005.             {
  3006.             n = mp->m_keylen;
  3007.             if (STRNCMP(mp->m_keys, keys,
  3008.                         (size_t)(n < len ? n : len)) == 0)
  3009.             {
  3010.                 showmap(mp, TRUE);
  3011.                 did_local = TRUE;
  3012.             }
  3013.             }
  3014.         }
  3015.         }
  3016.     }
  3017.     }
  3018. #endif
  3019.  
  3020.     /*
  3021.      * Find an entry in the maphash[] list that matches.
  3022.      * For :unmap we may loop two times: once to try to unmap an entry with a
  3023.      * matching 'from' part, a second time, if the first fails, to unmap an
  3024.      * entry with a matching 'to' part. This was done to allow ":ab foo bar"
  3025.      * to be unmapped by typing ":unab foo", where "foo" will be replaced by
  3026.      * "bar" because of the abbreviation.
  3027.      */
  3028.     for (round = 0; (round == 0 || maptype == 1) && round <= 1
  3029.                           && !did_it && !got_int; ++round)
  3030.     {
  3031.     /* need to loop over all hash lists */
  3032.     for (hash = 0; hash < 256 && !got_int; ++hash)
  3033.     {
  3034.         if (abbrev)
  3035.         {
  3036.         if (hash != 0)    /* there is only one abbreviation list */
  3037.             break;
  3038.         mpp = abbr_table;
  3039.         }
  3040.         else
  3041.         mpp = &(map_table[hash]);
  3042.         for (mp = *mpp; mp != NULL && !got_int; mp = *mpp)
  3043.         {
  3044.  
  3045.         if (!(mp->m_mode & mode))   /* skip entries with wrong mode */
  3046.         {
  3047.             mpp = &(mp->m_next);
  3048.             continue;
  3049.         }
  3050.         if (!haskey)            /* show all entries */
  3051.         {
  3052.             showmap(mp, map_table != maphash);
  3053.             did_it = TRUE;
  3054.         }
  3055.         else                /* do we have a match? */
  3056.         {
  3057.             if (round)        /* second round: Try unmap "rhs" string */
  3058.             {
  3059.             n = (int)STRLEN(mp->m_str);
  3060.             p = mp->m_str;
  3061.             }
  3062.             else
  3063.             {
  3064.             n = mp->m_keylen;
  3065.             p = mp->m_keys;
  3066.             }
  3067.             if (STRNCMP(p, keys, (size_t)(n < len ? n : len)) == 0)
  3068.             {
  3069.             if (maptype == 1)    /* delete entry */
  3070.             {
  3071.                 if (n != len)    /* not a full match */
  3072.                 {
  3073.                 mpp = &(mp->m_next);
  3074.                 continue;
  3075.                 }
  3076.                 /*
  3077.                  * We reset the indicated mode bits. If nothing is
  3078.                  * left the entry is deleted below.
  3079.                  */
  3080.                 mp->m_mode &= ~mode;
  3081.                 did_it = TRUE;    /* remember we did something */
  3082.             }
  3083.             else if (!hasarg)    /* show matching entry */
  3084.             {
  3085.                 showmap(mp, map_table != maphash);
  3086.                 did_it = TRUE;
  3087.             }
  3088.             else if (n != len)    /* new entry is ambigious */
  3089.             {
  3090.                 mpp = &(mp->m_next);
  3091.                 continue;
  3092.             }
  3093.             else if (unique)
  3094.             {
  3095.                 if (abbrev)
  3096.                 EMSG2(_("E226: abbreviation already exists for %s"),
  3097.                                        p);
  3098.                 else
  3099.                 EMSG2(_("E227: mapping already exists for %s"), p);
  3100.                 retval = 5;
  3101.                 goto theend;
  3102.             }
  3103.             else            /* new rhs for existing entry */
  3104.             {
  3105.                 mp->m_mode &= ~mode;    /* remove mode bits */
  3106.                 if (mp->m_mode == 0 && !did_it) /* reuse entry */
  3107.                 {
  3108.                 newstr = vim_strsave(rhs);
  3109.                 if (newstr == NULL)
  3110.                 {
  3111.                     retval = 4;        /* no mem */
  3112.                     goto theend;
  3113.                 }
  3114.                 vim_free(mp->m_str);
  3115.                 mp->m_str = newstr;
  3116.                 mp->m_noremap = noremap;
  3117.                 mp->m_silent = silent;
  3118.                 mp->m_mode = mode;
  3119.                 did_it = TRUE;
  3120.                 }
  3121.             }
  3122.             if (mp->m_mode == 0)    /* entry can be deleted */
  3123.             {
  3124.                 map_free(mpp);
  3125.                 continue;        /* continue with *mpp */
  3126.             }
  3127.  
  3128.             /*
  3129.              * May need to put this entry into another hash list.
  3130.              */
  3131.             new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
  3132.             if (!abbrev && new_hash != hash)
  3133.             {
  3134.                 *mpp = mp->m_next;
  3135.                 mp->m_next = map_table[new_hash];
  3136.                 map_table[new_hash] = mp;
  3137.  
  3138.                 continue;        /* continue with *mpp */
  3139.             }
  3140.             }
  3141.         }
  3142.         mpp = &(mp->m_next);
  3143.         }
  3144.     }
  3145.     }
  3146.  
  3147.     if (maptype == 1)                /* delete entry */
  3148.     {
  3149.     if (!did_it)
  3150.         retval = 2;                /* no match */
  3151.     goto theend;
  3152.     }
  3153.  
  3154.     if (!haskey || !hasarg)            /* print entries */
  3155.     {
  3156.     if (!did_it
  3157. #ifdef FEAT_LOCALMAP
  3158.         && !did_local
  3159. #endif
  3160.         )
  3161.     {
  3162.         if (abbrev)
  3163.         MSG(_("No abbreviation found"));
  3164.         else
  3165.         MSG(_("No mapping found"));
  3166.     }
  3167.     goto theend;                /* listing finished */
  3168.     }
  3169.  
  3170.     if (did_it)            /* have added the new entry already */
  3171.     goto theend;
  3172.  
  3173.     /*
  3174.      * Get here when adding a new entry to the maphash[] list or abbrlist.
  3175.      */
  3176.     mp = (mapblock_T *)alloc((unsigned)sizeof(mapblock_T));
  3177.     if (mp == NULL)
  3178.     {
  3179.     retval = 4;        /* no mem */
  3180.     goto theend;
  3181.     }
  3182.  
  3183.     /* If CTRL-C has been mapped, don't always use it for Interrupting */
  3184.     if (*keys == Ctrl_C)
  3185.     mapped_ctrl_c = TRUE;
  3186.  
  3187.     mp->m_keys = vim_strsave(keys);
  3188.     mp->m_str = vim_strsave(rhs);
  3189.     if (mp->m_keys == NULL || mp->m_str == NULL)
  3190.     {
  3191.     vim_free(mp->m_keys);
  3192.     vim_free(mp->m_str);
  3193.     vim_free(mp);
  3194.     retval = 4;    /* no mem */
  3195.     goto theend;
  3196.     }
  3197.     mp->m_keylen = (int)STRLEN(mp->m_keys);
  3198.     mp->m_noremap = noremap;
  3199.     mp->m_silent = silent;
  3200.     mp->m_mode = mode;
  3201.  
  3202.     /* add the new entry in front of the abbrlist or maphash[] list */
  3203.     if (abbrev)
  3204.     {
  3205.     mp->m_next = *abbr_table;
  3206.     *abbr_table = mp;
  3207.     }
  3208.     else
  3209.     {
  3210.     n = MAP_HASH(mp->m_mode, mp->m_keys[0]);
  3211.     mp->m_next = map_table[n];
  3212.     map_table[n] = mp;
  3213.     }
  3214.  
  3215. theend:
  3216.     vim_free(keys_buf);
  3217.     vim_free(arg_buf);
  3218.     return retval;
  3219. }
  3220.  
  3221. /*
  3222.  * Delete one entry from the abbrlist or maphash[].
  3223.  * "mpp" is a pointer to the m_next field of the PREVIOUS entry!
  3224.  */
  3225.     static void
  3226. map_free(mpp)
  3227.     mapblock_T    **mpp;
  3228. {
  3229.     mapblock_T    *mp;
  3230.  
  3231.     mp = *mpp;
  3232.     vim_free(mp->m_keys);
  3233.     vim_free(mp->m_str);
  3234.     *mpp = mp->m_next;
  3235.     vim_free(mp);
  3236. }
  3237.  
  3238. /*
  3239.  * Initialize maphash[] for first use.
  3240.  */
  3241.     static void
  3242. validate_maphash()
  3243. {
  3244.     if (!maphash_valid)
  3245.     {
  3246.     vim_memset(maphash, 0, sizeof(maphash));
  3247.     maphash_valid = TRUE;
  3248.     }
  3249. }
  3250.  
  3251. /*
  3252.  * Get the mapping mode from the command name.
  3253.  */
  3254.     int
  3255. get_map_mode(cmdp, forceit)
  3256.     char_u    **cmdp;
  3257.     int        forceit;
  3258. {
  3259.     char_u    *p;
  3260.     int        modec;
  3261.     int        mode;
  3262.  
  3263.     p = *cmdp;
  3264.     modec = *p++;
  3265.     if (modec == 'i')
  3266.     mode = INSERT;                /* :imap */
  3267.     else if (modec == 'l')
  3268.     mode = LANGMAP;                /* :lmap */
  3269.     else if (modec == 'c')
  3270.     mode = CMDLINE;                /* :cmap */
  3271.     else if (modec == 'n' && *p != 'o')            /* avoid :noremap */
  3272.     mode = NORMAL;                /* :nmap */
  3273.     else if (modec == 'v')
  3274.     mode = VISUAL;                /* :vmap */
  3275.     else if (modec == 'o')
  3276.     mode = OP_PENDING;            /* :omap */
  3277.     else
  3278.     {
  3279.     --p;
  3280.     if (forceit)
  3281.         mode = INSERT + CMDLINE;        /* :map ! */
  3282.     else
  3283.         mode = VISUAL + NORMAL + OP_PENDING;/* :map */
  3284.     }
  3285.  
  3286.     *cmdp = p;
  3287.     return mode;
  3288. }
  3289.  
  3290. /*
  3291.  * Clear all mappings or abbreviations.
  3292.  * 'abbr' should be FALSE for mappings, TRUE for abbreviations.
  3293.  */
  3294. /*ARGSUSED*/
  3295.     void
  3296. map_clear(cmdp, arg, forceit, abbr)
  3297.     char_u    *cmdp;
  3298.     char_u    *arg;
  3299.     int        forceit;
  3300.     int        abbr;
  3301. {
  3302.     mapblock_T    *mp, **mpp;
  3303.     int        mode;
  3304.     int        hash;
  3305.     int        new_hash;
  3306. #ifdef FEAT_LOCALMAP
  3307.     int        local;
  3308.  
  3309.     local = (STRCMP(arg, "<buffer>") == 0);
  3310.     if (!local && *arg != NUL)
  3311.     {
  3312.     EMSG(_(e_invarg));
  3313.     return;
  3314.     }
  3315. #endif
  3316.  
  3317.     validate_maphash();
  3318.  
  3319.     mode = get_map_mode(&cmdp, forceit);
  3320.  
  3321.     for (hash = 0; hash < 256; ++hash)
  3322.     {
  3323.     if (abbr)
  3324.     {
  3325.         if (hash)        /* there is only one abbrlist */
  3326.         break;
  3327. #ifdef FEAT_LOCALMAP
  3328.         if (local)
  3329.         mpp = &curbuf->b_first_abbr;
  3330.         else
  3331. #endif
  3332.         mpp = &first_abbr;
  3333.     }
  3334.     else
  3335.     {
  3336. #ifdef FEAT_LOCALMAP
  3337.         if (local)
  3338.         mpp = &curbuf->b_maphash[hash];
  3339.         else
  3340. #endif
  3341.         mpp = &maphash[hash];
  3342.     }
  3343.     while (*mpp != NULL)
  3344.     {
  3345.         mp = *mpp;
  3346.         if (mp->m_mode & mode)
  3347.         {
  3348.         mp->m_mode &= ~mode;
  3349.         if (mp->m_mode == 0) /* entry can be deleted */
  3350.         {
  3351.             map_free(mpp);
  3352.             continue;
  3353.         }
  3354.         /*
  3355.          * May need to put this entry into another hash list.
  3356.          */
  3357.         new_hash = MAP_HASH(mp->m_mode, mp->m_keys[0]);
  3358.         if (!abbr && new_hash != hash)
  3359.         {
  3360.             *mpp = mp->m_next;
  3361. #ifdef FEAT_LOCALMAP
  3362.             if (local)
  3363.             {
  3364.             mp->m_next = curbuf->b_maphash[new_hash];
  3365.             curbuf->b_maphash[new_hash] = mp;
  3366.             }
  3367.             else
  3368. #endif
  3369.             {
  3370.             mp->m_next = maphash[new_hash];
  3371.             maphash[new_hash] = mp;
  3372.             }
  3373.             continue;        /* continue with *mpp */
  3374.         }
  3375.         }
  3376.         mpp = &(mp->m_next);
  3377.     }
  3378.     }
  3379. }
  3380.  
  3381.     static void
  3382. showmap(mp, local)
  3383.     mapblock_T    *mp;
  3384.     int        local;        /* TRUE for buffer-local map */
  3385. {
  3386.     int len = 1;
  3387.  
  3388.     if (msg_didout)
  3389.     msg_putchar('\n');
  3390.     if ((mp->m_mode & (INSERT + CMDLINE)) == INSERT + CMDLINE)
  3391.     msg_putchar('!');            /* :map! */
  3392.     else if (mp->m_mode & INSERT)
  3393.     msg_putchar('i');            /* :imap */
  3394.     else if (mp->m_mode & LANGMAP)
  3395.     msg_putchar('l');            /* :lmap */
  3396.     else if (mp->m_mode & CMDLINE)
  3397.     msg_putchar('c');            /* :cmap */
  3398.     else if ((mp->m_mode & (NORMAL + VISUAL + OP_PENDING))
  3399.                           == NORMAL + VISUAL + OP_PENDING)
  3400.     msg_putchar(' ');            /* :map */
  3401.     else
  3402.     {
  3403.     len = 0;
  3404.     if (mp->m_mode & NORMAL)
  3405.     {
  3406.         msg_putchar('n');        /* :nmap */
  3407.         ++len;
  3408.     }
  3409.     if (mp->m_mode & OP_PENDING)
  3410.     {
  3411.         msg_putchar('o');        /* :omap */
  3412.         ++len;
  3413.     }
  3414.     if (mp->m_mode & VISUAL)
  3415.     {
  3416.         msg_putchar('v');        /* :vmap */
  3417.         ++len;
  3418.     }
  3419.     }
  3420.     while (++len <= 3)
  3421.     msg_putchar(' ');
  3422.  
  3423.     /* Get length of what we write */
  3424.     len = msg_outtrans_special(mp->m_keys, TRUE);
  3425.     do
  3426.     {
  3427.     msg_putchar(' ');        /* padd with blanks */
  3428.     ++len;
  3429.     } while (len < 12);
  3430.  
  3431.     if (mp->m_noremap == REMAP_NONE)
  3432.     msg_puts_attr((char_u *)"*", hl_attr(HLF_8));
  3433.     else if (mp->m_noremap == REMAP_SCRIPT)
  3434.     msg_puts_attr((char_u *)"&", hl_attr(HLF_8));
  3435.     else
  3436.     msg_putchar(' ');
  3437.  
  3438.     if (local)
  3439.     msg_putchar('@');
  3440.     else
  3441.     msg_putchar(' ');
  3442.  
  3443.     /* Use FALSE below if we only want things like <Up> to show up as such on
  3444.      * the rhs, and not M-x etc, TRUE gets both -- webb
  3445.      */
  3446.     if (*mp->m_str == NUL)
  3447.     msg_puts_attr((char_u *)"<Nop>", hl_attr(HLF_8));
  3448.     else
  3449.     msg_outtrans_special(mp->m_str, FALSE);
  3450.     out_flush();            /* show one line at a time */
  3451. }
  3452.  
  3453. #if defined(FEAT_EVAL) || defined(PROTO)
  3454. /*
  3455.  * Return TRUE if a map exists that has "str" in the rhs for mode "modechars".
  3456.  * Recognize termcap codes in "str".
  3457.  * Also checks mappings local to the current buffer.
  3458.  */
  3459.     int
  3460. map_to_exists(str, modechars)
  3461.     char_u    *str;
  3462.     char_u    *modechars;
  3463. {
  3464.     int        mode = 0;
  3465.     char_u    *rhs;
  3466.     char_u    *buf;
  3467.     int        retval;
  3468.  
  3469.     rhs = replace_termcodes(str, &buf, FALSE, TRUE);
  3470.  
  3471.     if (vim_strchr(modechars, 'n') != NULL)
  3472.     mode |= NORMAL;
  3473.     if (vim_strchr(modechars, 'v') != NULL)
  3474.     mode |= VISUAL;
  3475.     if (vim_strchr(modechars, 'o') != NULL)
  3476.     mode |= OP_PENDING;
  3477.     if (vim_strchr(modechars, 'i') != NULL)
  3478.     mode |= INSERT;
  3479.     if (vim_strchr(modechars, 'l') != NULL)
  3480.     mode |= LANGMAP;
  3481.     if (vim_strchr(modechars, 'c') != NULL)
  3482.     mode |= CMDLINE;
  3483.  
  3484.     retval = map_to_exists_mode(rhs, mode);
  3485.     vim_free(buf);
  3486.  
  3487.     return retval;
  3488. }
  3489. #endif
  3490.  
  3491. /*
  3492.  * Return TRUE if a map exists that has "str" in the rhs for mode "mode".
  3493.  * Also checks mappings local to the current buffer.
  3494.  */
  3495.     int
  3496. map_to_exists_mode(rhs, mode)
  3497.     char_u    *rhs;
  3498.     int        mode;
  3499. {
  3500.     mapblock_T    *mp;
  3501.     int        hash;
  3502. # ifdef FEAT_LOCALMAP
  3503.     int        expand_buffer = FALSE;
  3504.  
  3505.     validate_maphash();
  3506.  
  3507.     /* Do it twice: once for global maps and once for local maps. */
  3508.     for (;;)
  3509.     {
  3510. # endif
  3511.     for (hash = 0; hash < 256; ++hash)
  3512.     {
  3513. # ifdef FEAT_LOCALMAP
  3514.         if (expand_buffer)
  3515.         mp = curbuf->b_maphash[hash];
  3516.         else
  3517. # endif
  3518.         mp = maphash[hash];
  3519.         for (; mp; mp = mp->m_next)
  3520.         {
  3521.         if ((mp->m_mode & mode)
  3522.             && strstr((char *)mp->m_str, (char *)rhs) != NULL)
  3523.             return TRUE;
  3524.         }
  3525.     }
  3526. # ifdef FEAT_LOCALMAP
  3527.     if (expand_buffer)
  3528.         break;
  3529.     expand_buffer = TRUE;
  3530.     }
  3531. # endif
  3532.  
  3533.     return FALSE;
  3534. }
  3535.  
  3536. #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
  3537. /*
  3538.  * Used below when expanding mapping/abbreviation names.
  3539.  */
  3540. static int    expand_mapmodes = 0;
  3541. static int    expand_isabbrev = 0;
  3542. #ifdef FEAT_LOCALMAP
  3543. static int    expand_buffer = FALSE;
  3544. #endif
  3545.  
  3546. /*
  3547.  * Work out what to complete when doing command line completion of mapping
  3548.  * or abbreviation names.
  3549.  */
  3550.     char_u *
  3551. set_context_in_map_cmd(xp, cmd, arg, forceit, isabbrev, isunmap, cmdidx)
  3552.     expand_T    *xp;
  3553.     char_u    *cmd;
  3554.     char_u    *arg;
  3555.     int        forceit;    /* TRUE if '!' given */
  3556.     int        isabbrev;    /* TRUE if abbreviation */
  3557.     int        isunmap;    /* TRUE if unmap/unabbrev command */
  3558.     cmdidx_T    cmdidx;
  3559. {
  3560.     if (forceit && cmdidx != CMD_map && cmdidx != CMD_unmap)
  3561.     xp->xp_context = EXPAND_NOTHING;
  3562.     else
  3563.     {
  3564.     if (isunmap)
  3565.         expand_mapmodes = get_map_mode(&cmd, forceit || isabbrev);
  3566.     else
  3567.     {
  3568.         expand_mapmodes = INSERT + CMDLINE;
  3569.         if (!isabbrev)
  3570.         expand_mapmodes += VISUAL + NORMAL + OP_PENDING;
  3571.     }
  3572.     expand_isabbrev = isabbrev;
  3573.     xp->xp_context = EXPAND_MAPPINGS;
  3574. #ifdef FEAT_LOCALMAP
  3575.     expand_buffer = FALSE;
  3576.     for (;;)
  3577.     {
  3578.         if (STRNCMP(arg, "<buffer>", 8) == 0)
  3579.         {
  3580.         expand_buffer = TRUE;
  3581.         arg = skipwhite(arg + 8);
  3582.         continue;
  3583.         }
  3584. #endif
  3585.         if (STRNCMP(arg, "<unique>", 8) == 0)
  3586.         {
  3587.         arg = skipwhite(arg + 8);
  3588. #ifdef FEAT_LOCALMAP
  3589.         continue;
  3590. #endif
  3591.         }
  3592. #ifdef FEAT_LOCALMAP
  3593.         break;
  3594.     }
  3595. #endif
  3596.     xp->xp_pattern = arg;
  3597.     }
  3598.  
  3599.     return NULL;
  3600. }
  3601.  
  3602. /*
  3603.  * Find all mapping/abbreviation names that match regexp 'prog'.
  3604.  * For command line expansion of ":[un]map" and ":[un]abbrev" in all modes.
  3605.  * Return OK if matches found, FAIL otherwise.
  3606.  */
  3607.     int
  3608. ExpandMappings(regmatch, num_file, file)
  3609.     regmatch_T    *regmatch;
  3610.     int        *num_file;
  3611.     char_u    ***file;
  3612. {
  3613.     mapblock_T    *mp;
  3614.     int        hash;
  3615.     int        count;
  3616.     int        round;
  3617.     char_u    *p;
  3618.  
  3619.     validate_maphash();
  3620.  
  3621.     *num_file = 0;            /* return values in case of FAIL */
  3622.     *file = NULL;
  3623.  
  3624.     /*
  3625.      * round == 1: Count the matches.
  3626.      * round == 2: Build the array to keep the matches.
  3627.      */
  3628.     for (round = 1; round <= 2; ++round)
  3629.     {
  3630.     count = 0;
  3631. #ifdef FEAT_LOCALMAP
  3632.     if (!expand_buffer)
  3633.     {
  3634.         if (vim_regexec(regmatch, (char_u *)"<buffer>", (colnr_T)0))
  3635.         {
  3636.         if (round == 1)
  3637.             ++count;
  3638.         else
  3639.             (*file)[count++] = vim_strsave((char_u *)"<buffer>");
  3640.         }
  3641.     }
  3642. #endif
  3643.     if (vim_regexec(regmatch, (char_u *)"<unique>", (colnr_T)0))
  3644.     {
  3645.         if (round == 1)
  3646.         ++count;
  3647.         else
  3648.         (*file)[count++] = vim_strsave((char_u *)"<unique>");
  3649.     }
  3650.     for (hash = 0; hash < 256; ++hash)
  3651.     {
  3652.         if (expand_isabbrev)
  3653.         {
  3654.         if (hash)    /* only one abbrev list */
  3655.             break; /* for (hash) */
  3656.         mp = first_abbr;
  3657.         }
  3658. #ifdef FEAT_LOCALMAP
  3659.         else if (expand_buffer)
  3660.         mp = curbuf->b_maphash[hash];
  3661. #endif
  3662.         else
  3663.         mp = maphash[hash];
  3664.         for (; mp; mp = mp->m_next)
  3665.         {
  3666.         if (mp->m_mode & expand_mapmodes)
  3667.         {
  3668.             p = translate_mapping(mp->m_keys, TRUE);
  3669.             if (p != NULL && vim_regexec(regmatch, p, (colnr_T)0))
  3670.             {
  3671.             if (round == 1)
  3672.                 ++count;
  3673.             else
  3674.             {
  3675.                 (*file)[count++] = p;
  3676.                 p = NULL;
  3677.             }
  3678.             }
  3679.             vim_free(p);
  3680.         }
  3681.         } /* for (mp) */
  3682.     } /* for (hash) */
  3683.  
  3684.     if (count == 0)            /* no match found */
  3685.         break; /* for (round) */
  3686.  
  3687.     if (round == 1)
  3688.     {
  3689.         *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
  3690.         if (*file == NULL)
  3691.         return FAIL;
  3692.     }
  3693.     } /* for (round) */
  3694.  
  3695.     /* Sort the matches */
  3696.     sort_strings(*file, count);
  3697.  
  3698.     /* Remove multiple entries */
  3699.     {
  3700.     char_u    **ptr1 = *file;
  3701.     char_u    **ptr2 = ptr1 + 1;
  3702.     char_u    **ptr3 = ptr1 + count;
  3703.  
  3704.     while (ptr2 < ptr3)
  3705.     {
  3706.         if (STRCMP(*ptr1, *ptr2))
  3707.         *++ptr1 = *ptr2++;
  3708.         else
  3709.         {
  3710.         vim_free(*ptr2++);
  3711.         count--;
  3712.         }
  3713.     }
  3714.     }
  3715.  
  3716.     *num_file = count;
  3717.     return (count == 0 ? FAIL : OK);
  3718. }
  3719. #endif /* FEAT_CMDL_COMPL */
  3720.  
  3721. /*
  3722.  * Check for an abbreviation.
  3723.  * Cursor is at ptr[col]. When inserting, mincol is where insert started.
  3724.  * "c" is the character typed before check_abbr was called.
  3725.  *
  3726.  * Historic vi practice: The last character of an abbreviation must be an id
  3727.  * character ([a-zA-Z0-9_]). The characters in front of it must be all id
  3728.  * characters or all non-id characters. This allows for abbr. "#i" to
  3729.  * "#include".
  3730.  *
  3731.  * Vim addition: Allow for abbreviations that end in a non-keyword character.
  3732.  * Then there must be white space before the abbr.
  3733.  *
  3734.  * return TRUE if there is an abbreviation, FALSE if not
  3735.  */
  3736.     int
  3737. check_abbr(c, ptr, col, mincol)
  3738.     int        c;
  3739.     char_u    *ptr;
  3740.     int        col;
  3741.     int        mincol;
  3742. {
  3743.     int        len;
  3744.     int        j;
  3745.     char_u    tb[4];
  3746.     mapblock_T    *mp;
  3747. #ifdef FEAT_LOCALMAP
  3748.     mapblock_T    *mp2;
  3749. #endif
  3750.     int        is_id = TRUE;
  3751.     int        vim_abbr;
  3752.  
  3753.     if (typebuf.tb_no_abbr_cnt)        /* abbrev. are not recursive */
  3754.     return FALSE;
  3755.  
  3756.     /*
  3757.      * Check for word before the cursor: If it ends in a keyword char all
  3758.      * chars before it must be al keyword chars or non-keyword chars, but not
  3759.      * white space. If it ends in a non-keyword char we accept any characters
  3760.      * before it except white space.
  3761.      */
  3762.     if (col == 0)                /* cannot be an abbr. */
  3763.     return FALSE;
  3764.  
  3765. #ifdef FEAT_MBYTE
  3766.     if (has_mbyte)
  3767.     {
  3768.     char_u *p;
  3769.  
  3770.     p = mb_prevptr(ptr, ptr + col);
  3771.     if (!vim_iswordp(p))
  3772.         vim_abbr = TRUE;            /* Vim added abbr. */
  3773.     else
  3774.     {
  3775.         vim_abbr = FALSE;            /* vi compatible abbr. */
  3776.         if (p > ptr)
  3777.         is_id = vim_iswordp(mb_prevptr(ptr, p));
  3778.     }
  3779.     while (p > ptr)
  3780.     {
  3781.         p = mb_prevptr(ptr, p);
  3782.         if (vim_isspace(*p) || (!vim_abbr && is_id != vim_iswordp(p)))
  3783.         {
  3784.         p += (*mb_ptr2len_check)(p);
  3785.         break;
  3786.         }
  3787.     }
  3788.     len = (int)(p - ptr);
  3789.     }
  3790.     else
  3791. #endif
  3792.     {
  3793.     if (!vim_iswordc(ptr[col - 1]))
  3794.         vim_abbr = TRUE;            /* Vim added abbr. */
  3795.     else
  3796.     {
  3797.         vim_abbr = FALSE;            /* vi compatible abbr. */
  3798.         if (col > 1)
  3799.         is_id = vim_iswordc(ptr[col - 2]);
  3800.     }
  3801.     for (len = col - 1; len > 0 && !vim_isspace(ptr[len - 1]) &&
  3802.         (vim_abbr || is_id == vim_iswordc(ptr[len - 1])); --len)
  3803.         ;
  3804.     }
  3805.  
  3806.     if (len < mincol)
  3807.     len = mincol;
  3808.     if (len < col)        /* there is a word in front of the cursor */
  3809.     {
  3810.     ptr += len;
  3811.     len = col - len;
  3812. #ifdef FEAT_LOCALMAP
  3813.     mp = curbuf->b_first_abbr;
  3814.     mp2 = first_abbr;
  3815.     if (mp == NULL)
  3816.     {
  3817.         mp = mp2;
  3818.         mp2 = NULL;
  3819.     }
  3820. #else
  3821.     mp = first_abbr;
  3822. #endif
  3823.     for ( ; mp;
  3824. #ifdef FEAT_LOCALMAP
  3825.         mp->m_next == NULL ? (mp = mp2, mp2 = NULL) :
  3826. #endif
  3827.         (mp = mp->m_next))
  3828.     {
  3829.         /* find entries with right mode and keys */
  3830.         if (       (mp->m_mode & State)
  3831.             && mp->m_keylen == len
  3832.             && !STRNCMP(mp->m_keys, ptr, (size_t)len))
  3833.         break;
  3834.     }
  3835.     if (mp != NULL)
  3836.     {
  3837.         /*
  3838.          * Found a match:
  3839.          * Insert the rest of the abbreviation in typebuf.tb_buf[].
  3840.          * This goes from end to start.
  3841.          *
  3842.          * Characters 0x000 - 0x100: normal chars, may need CTRL-V,
  3843.          * except K_SPECIAL: Becomes K_SPECIAL KS_SPECIAL KE_FILLER
  3844.          * Characters where IS_SPECIAL() == TRUE: key codes, need
  3845.          * K_SPECIAL. Other characters (with ABBR_OFF): don't use CTRL-V.
  3846.          *
  3847.          * Character CTRL-] is treated specially - it completes the
  3848.          * abbreviation, but is not inserted into the input stream.
  3849.          */
  3850.         j = 0;
  3851.                         /* special key code, split up */
  3852.         if (c != Ctrl_RSB)
  3853.         {
  3854.         if (IS_SPECIAL(c) || c == K_SPECIAL)
  3855.         {
  3856.             tb[j++] = K_SPECIAL;
  3857.             tb[j++] = K_SECOND(c);
  3858.             c = K_THIRD(c);
  3859.         }
  3860.         else if (c < ABBR_OFF && (c < ' ' || c > '~'))
  3861.             tb[j++] = Ctrl_V;    /* special char needs CTRL-V */
  3862.         tb[j++] = c;
  3863.         tb[j] = NUL;
  3864.                         /* insert the last typed char */
  3865.         (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
  3866.         }
  3867.                         /* insert the to string */
  3868.         (void)ins_typebuf(mp->m_str, mp->m_noremap, 0, TRUE, mp->m_silent);
  3869.                         /* no abbrev. for these chars */
  3870.         typebuf.tb_no_abbr_cnt += (int)STRLEN(mp->m_str) + j + 1;
  3871.  
  3872.         tb[0] = Ctrl_H;
  3873.         tb[1] = NUL;
  3874.         while (len--)            /* delete the from string */
  3875.         (void)ins_typebuf(tb, 1, 0, TRUE, mp->m_silent);
  3876.         return TRUE;
  3877.     }
  3878.     }
  3879.     return FALSE;
  3880. }
  3881.  
  3882. /*
  3883.  * Write map commands for the current mappings to an .exrc file.
  3884.  * Return FAIL on error, OK otherwise.
  3885.  */
  3886.     int
  3887. makemap(fd, buf)
  3888.     FILE    *fd;
  3889.     buf_T    *buf;        /* buffer for local mappings or NULL */
  3890. {
  3891.     mapblock_T    *mp;
  3892.     char_u    c1, c2;
  3893.     char_u    *p;
  3894.     char    *cmd;
  3895.     int        abbr;
  3896.     int        hash;
  3897.     int        did_cpo = FALSE;
  3898.     int        i;
  3899.  
  3900.     validate_maphash();
  3901.  
  3902.     /*
  3903.      * Do the loop twice: Once for mappings, once for abbreviations.
  3904.      * Then loop over all map hash lists.
  3905.      */
  3906.     for (abbr = 0; abbr < 2; ++abbr)
  3907.     for (hash = 0; hash < 256; ++hash)
  3908.     {
  3909.         if (abbr)
  3910.         {
  3911.         if (hash)        /* there is only one abbr list */
  3912.             break;
  3913. #ifdef FEAT_LOCALMAP
  3914.         if (buf != NULL)
  3915.             mp = buf->b_first_abbr;
  3916.         else
  3917. #endif
  3918.             mp = first_abbr;
  3919.         }
  3920.         else
  3921.         {
  3922. #ifdef FEAT_LOCALMAP
  3923.         if (buf != NULL)
  3924.             mp = buf->b_maphash[hash];
  3925.         else
  3926. #endif
  3927.             mp = maphash[hash];
  3928.         }
  3929.  
  3930.         for ( ; mp; mp = mp->m_next)
  3931.         {
  3932.         /* skip script-local mappings */
  3933.         if (mp->m_noremap == REMAP_SCRIPT)
  3934.             continue;
  3935.  
  3936.         /* skip mappings that contain a <SNR> (script-local thing),
  3937.          * they probably don't work when loaded again */
  3938.         for (p = mp->m_str; *p != NUL; ++p)
  3939.             if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
  3940.                                && p[2] == (int)KE_SNR)
  3941.             break;
  3942.         if (*p != NUL)
  3943.             continue;
  3944.  
  3945.         c1 = NUL;
  3946.         c2 = NUL;
  3947.         if (abbr)
  3948.             cmd = "abbr";
  3949.         else
  3950.             cmd = "map";
  3951.         switch (mp->m_mode)
  3952.         {
  3953.             case NORMAL + VISUAL + OP_PENDING:
  3954.             break;
  3955.             case NORMAL:
  3956.             c1 = 'n';
  3957.             break;
  3958.             case VISUAL:
  3959.             c1 = 'v';
  3960.             break;
  3961.             case OP_PENDING:
  3962.             c1 = 'o';
  3963.             break;
  3964.             case NORMAL + VISUAL:
  3965.             c1 = 'n';
  3966.             c2 = 'v';
  3967.             break;
  3968.             case VISUAL + OP_PENDING:
  3969.             c1 = 'v';
  3970.             c2 = 'o';
  3971.             break;
  3972.             case NORMAL + OP_PENDING:
  3973.             c1 = 'n';
  3974.             c2 = 'o';
  3975.             break;
  3976.             case CMDLINE + INSERT:
  3977.             if (!abbr)
  3978.                 cmd = "map!";
  3979.             break;
  3980.             case CMDLINE:
  3981.             c1 = 'c';
  3982.             break;
  3983.             case INSERT:
  3984.             c1 = 'i';
  3985.             break;
  3986.             case LANGMAP:
  3987.             c1 = 'l';
  3988.             break;
  3989.             default:
  3990.             EMSG(_("E228: makemap: Illegal mode"));
  3991.             return FAIL;
  3992.         }
  3993.         do    /* may do this twice if c2 is set */
  3994.         {
  3995.             /* When outputting <> form, need to make sure that 'cpo'
  3996.              * is set to the Vim default. */
  3997.             if (!did_cpo)
  3998.             {
  3999.             if (*mp->m_str == NUL)        /* will use <Nop> */
  4000.                 did_cpo = TRUE;
  4001.             else
  4002.                 for (i = 0; i < 2; ++i)
  4003.                 for (p = (i ? mp->m_str : mp->m_keys); *p; ++p)
  4004.                     if (*p == K_SPECIAL || *p == NL)
  4005.                     did_cpo = TRUE;
  4006.             if (did_cpo)
  4007.             {
  4008.                 if (fprintf(fd, "let s:cpo_save=&cpo") < 0
  4009.                     || put_eol(fd) < 0
  4010.                     || fprintf(fd, "set cpo&vim") < 0
  4011.                     || put_eol(fd) < 0)
  4012.                 return FAIL;
  4013.             }
  4014.             }
  4015.             if (c1 && putc(c1, fd) < 0)
  4016.             return FAIL;
  4017.             if (mp->m_noremap != REMAP_YES && fprintf(fd, "nore") < 0)
  4018.             return FAIL;
  4019.             if (fprintf(fd, cmd) < 0)
  4020.             return FAIL;
  4021.             if (buf != NULL && fputs(" <buffer>", fd) < 0)
  4022.             return FAIL;
  4023.  
  4024.             if (       putc(' ', fd) < 0
  4025.                 || put_escstr(fd, mp->m_keys, 0) == FAIL
  4026.                 || putc(' ', fd) < 0
  4027.                 || put_escstr(fd, mp->m_str, 1) == FAIL
  4028.                 || put_eol(fd) < 0)
  4029.             return FAIL;
  4030.             c1 = c2;
  4031.             c2 = NUL;
  4032.         }
  4033.         while (c1);
  4034.         }
  4035.     }
  4036.  
  4037.     if (did_cpo)
  4038.     if (fprintf(fd, "let &cpo=s:cpo_save") < 0
  4039.         || put_eol(fd) < 0
  4040.         || fprintf(fd, "unlet s:cpo_save") < 0
  4041.         || put_eol(fd) < 0)
  4042.         return FAIL;
  4043.     return OK;
  4044. }
  4045.  
  4046. /*
  4047.  * write escape string to file
  4048.  * "what": 0 for :map lhs, 1 for :map rhs, 2 for :set
  4049.  *
  4050.  * return FAIL for failure, OK otherwise
  4051.  */
  4052.     int
  4053. put_escstr(fd, str, what)
  4054.     FILE    *fd;
  4055.     char_u    *str;
  4056.     int        what;
  4057. {
  4058.     int        c;
  4059.     int        modifiers;
  4060.  
  4061.     /* :map xx <Nop> */
  4062.     if (*str == NUL && what == 1)
  4063.     {
  4064.     if (fprintf(fd, "<Nop>") < 0)
  4065.         return FAIL;
  4066.     return OK;
  4067.     }
  4068.  
  4069.     for ( ; *str != NUL; ++str)
  4070.     {
  4071. #ifdef FEAT_MBYTE
  4072.     char_u    *p;
  4073.  
  4074.     /* Check for a multi-byte character, which may contain escaped
  4075.      * K_SPECIAL and CSI bytes */
  4076.     p = mb_unescape(&str);
  4077.     if (p != NULL)
  4078.     {
  4079.         while (*p != NUL)
  4080.         if (putc(*p++, fd) < 0)
  4081.             return FAIL;
  4082.         --str;
  4083.         continue;
  4084.     }
  4085. #endif
  4086.  
  4087.     c = *str;
  4088.     /*
  4089.      * Special key codes have to be translated to be able to make sense
  4090.      * when they are read back.
  4091.      */
  4092.     if (c == K_SPECIAL && what != 2)
  4093.     {
  4094.         modifiers = 0x0;
  4095.         if (str[1] == KS_MODIFIER)
  4096.         {
  4097.         modifiers = str[2];
  4098.         str += 3;
  4099.         c = *str;
  4100.         }
  4101.         if (c == K_SPECIAL)
  4102.         {
  4103.         c = TO_SPECIAL(str[1], str[2]);
  4104.         str += 2;
  4105.         }
  4106.         if (IS_SPECIAL(c) || modifiers)    /* special key */
  4107.         {
  4108.         if (fprintf(fd, (char *)get_special_key_name(c, modifiers)) < 0)
  4109.             return FAIL;
  4110.         continue;
  4111.         }
  4112.     }
  4113.  
  4114.     /*
  4115.      * A '\n' in a map command should be written as <NL>.
  4116.      * A '\n' in a set command should be written as \^V^J.
  4117.      */
  4118.     if (c == NL)
  4119.     {
  4120.         if (what == 2)
  4121.         {
  4122.         if (fprintf(fd, IF_EB("\\\026\n", "\\" CTRL_V_STR "\n")) < 0)
  4123.             return FAIL;
  4124.         }
  4125.         else
  4126.         {
  4127.         if (fprintf(fd, "<NL>") < 0)
  4128.             return FAIL;
  4129.         }
  4130.         continue;
  4131.     }
  4132.  
  4133.     /*
  4134.      * Some characters have to be escaped with CTRL-V to
  4135.      * prevent them from misinterpreted in DoOneCmd().
  4136.      * A space, Tab and '"' has to be escaped with a backslash to
  4137.      * prevent it to be misinterpreted in do_set().
  4138.      * A '<' has to be escaped with a CTRL-V to prevent it being
  4139.      * interpreted as the start of a special key name.
  4140.      * A space in the lhs of a :map needs a CTRL-V.
  4141.      */
  4142.     if (what == 2 && (vim_iswhite(c) || c == '"' || c == '\\'))
  4143.     {
  4144.         if (putc('\\', fd) < 0)
  4145.         return FAIL;
  4146.     }
  4147.     else if (c < ' ' || c > '~' || c == '|' || (what != 2 && c == '<')
  4148.                            || (what == 0 && c == ' '))
  4149.     {
  4150.         if (putc(Ctrl_V, fd) < 0)
  4151.         return FAIL;
  4152.     }
  4153.     if (putc(c, fd) < 0)
  4154.         return FAIL;
  4155.     }
  4156.     return OK;
  4157. }
  4158.  
  4159. /*
  4160.  * Check all mappings for the presence of special key codes.
  4161.  * Used after ":set term=xxx".
  4162.  */
  4163.     void
  4164. check_map_keycodes()
  4165. {
  4166.     mapblock_T    *mp;
  4167.     char_u    *p;
  4168.     int        i;
  4169.     char_u    buf[3];
  4170.     char_u    *save_name;
  4171.     int        abbr;
  4172.     int        hash;
  4173. #ifdef FEAT_LOCALMAP
  4174.     buf_T    *bp;
  4175. #endif
  4176.  
  4177.     validate_maphash();
  4178.     save_name = sourcing_name;
  4179.     sourcing_name = (char_u *)"mappings"; /* avoids giving error messages */
  4180.  
  4181. #ifdef FEAT_LOCALMAP
  4182.     /* This this once for each buffer, and then once for global
  4183.      * mappings/abbreviations with bp == NULL */
  4184.     for (bp = firstbuf; ; bp = bp->b_next)
  4185.     {
  4186. #endif
  4187.     /*
  4188.      * Do the loop twice: Once for mappings, once for abbreviations.
  4189.      * Then loop over all map hash lists.
  4190.      */
  4191.     for (abbr = 0; abbr <= 1; ++abbr)
  4192.         for (hash = 0; hash < 256; ++hash)
  4193.         {
  4194.         if (abbr)
  4195.         {
  4196.             if (hash)        /* there is only one abbr list */
  4197.             break;
  4198. #ifdef FEAT_LOCALMAP
  4199.             if (bp != NULL)
  4200.             mp = bp->b_first_abbr;
  4201.             else
  4202. #endif
  4203.             mp = first_abbr;
  4204.         }
  4205.         else
  4206.         {
  4207. #ifdef FEAT_LOCALMAP
  4208.             if (bp != NULL)
  4209.             mp = bp->b_maphash[hash];
  4210.             else
  4211. #endif
  4212.             mp = maphash[hash];
  4213.         }
  4214.         for ( ; mp != NULL; mp = mp->m_next)
  4215.         {
  4216.             for (i = 0; i <= 1; ++i)    /* do this twice */
  4217.             {
  4218.             if (i == 0)
  4219.                 p = mp->m_keys;    /* once for the "from" part */
  4220.             else
  4221.                 p = mp->m_str;    /* and once for the "to" part */
  4222.             while (*p)
  4223.             {
  4224.                 if (*p == K_SPECIAL)
  4225.                 {
  4226.                 ++p;
  4227.                 if (*p < 128)   /* for "normal" tcap entries */
  4228.                 {
  4229.                     buf[0] = p[0];
  4230.                     buf[1] = p[1];
  4231.                     buf[2] = NUL;
  4232.                     (void)add_termcap_entry(buf, FALSE);
  4233.                 }
  4234.                 ++p;
  4235.                 }
  4236.                 ++p;
  4237.             }
  4238.             }
  4239.         }
  4240.         }
  4241. #ifdef FEAT_LOCALMAP
  4242.     if (bp == NULL)
  4243.         break;
  4244.     }
  4245. #endif
  4246.     sourcing_name = save_name;
  4247. }
  4248.  
  4249. #ifdef FEAT_EVAL
  4250. /*
  4251.  * Check the string "keys" against the lhs of all mappings
  4252.  * Return pointer to rhs of mapping (mapblock->m_str)
  4253.  * NULL otherwise
  4254.  */
  4255.     char_u *
  4256. check_map(keys, mode, exact)
  4257.     char_u    *keys;
  4258.     int        mode;
  4259.     int        exact;        /* require exact match */
  4260. {
  4261.     int        hash;
  4262.     int        len, minlen;
  4263.     mapblock_T    *mp;
  4264. #ifdef FEAT_LOCALMAP
  4265.     int        local;
  4266. #endif
  4267.  
  4268.     validate_maphash();
  4269.  
  4270.     len = (int)STRLEN(keys);
  4271. #ifdef FEAT_LOCALMAP
  4272.     for (local = 1; local >= 0; --local)
  4273. #endif
  4274.     /* loop over all hash lists */
  4275.     for (hash = 0; hash < 256; ++hash)
  4276.     {
  4277. #ifdef FEAT_LOCALMAP
  4278.         if (local)
  4279.         mp = curbuf->b_maphash[hash];
  4280.         else
  4281. #endif
  4282.         mp = maphash[hash];
  4283.         for ( ; mp != NULL; mp = mp->m_next)
  4284.         {
  4285.         /* skip entries with wrong mode, wrong length and not matching
  4286.          * ones */
  4287.         if (mp->m_keylen < len)
  4288.             minlen = mp->m_keylen;
  4289.         else
  4290.             minlen = len;
  4291.         if ((mp->m_mode & mode)
  4292.             && (!exact || mp->m_keylen == len)
  4293.             && STRNCMP(mp->m_keys, keys, minlen) == 0)
  4294.             return mp->m_str;
  4295.         }
  4296.     }
  4297.  
  4298.     return NULL;
  4299. }
  4300. #endif
  4301.  
  4302. /*
  4303.  * Default mappings for some often used keys.
  4304.  */
  4305. static struct initmap
  4306. {
  4307.     char_u    *arg;
  4308.     int        mode;
  4309. } initmappings[] =
  4310. {
  4311. #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
  4312.     /* Use the Windows (CUA) keybindings. */
  4313. # ifdef FEAT_GUI
  4314.     {(char_u *)"<C-PageUp> H", NORMAL+VISUAL},
  4315.     {(char_u *)"<C-PageUp> <C-O>H",INSERT},
  4316.     {(char_u *)"<C-PageDown> L$", NORMAL+VISUAL},
  4317.     {(char_u *)"<C-PageDown> <C-O>L<C-O>$", INSERT},
  4318.  
  4319.     /* paste, copy and cut */
  4320.     {(char_u *)"<S-Insert> \"*P", NORMAL},
  4321.     {(char_u *)"<S-Insert> \"-d\"*P", VISUAL},
  4322.     {(char_u *)"<S-Insert> <C-R><C-O>*", INSERT+CMDLINE},
  4323.     {(char_u *)"<C-Insert> \"*y", VISUAL},
  4324.     {(char_u *)"<S-Del> \"*d", VISUAL},
  4325.     {(char_u *)"<C-Del> \"*d", VISUAL},
  4326.     {(char_u *)"<C-X> \"*d", VISUAL},
  4327.     /* Missing: CTRL-C (cancel) and CTRL-V (block selection) */
  4328. # else
  4329.     {(char_u *)"\316\204 H", NORMAL+VISUAL},    /* CTRL-PageUp is "H" */
  4330.     {(char_u *)"\316\204 \017H",INSERT},        /* CTRL-PageUp is "^OH"*/
  4331.     {(char_u *)"\316v L$", NORMAL+VISUAL},        /* CTRL-PageDown is "L$" */
  4332.     {(char_u *)"\316v \017L\017$", INSERT},        /* CTRL-PageDown ="^OL^O$"*/
  4333.     {(char_u *)"\316w <C-Home>", NORMAL+VISUAL},
  4334.     {(char_u *)"\316w <C-Home>", INSERT+CMDLINE},
  4335.     {(char_u *)"\316u <C-End>", NORMAL+VISUAL},
  4336.     {(char_u *)"\316u <C-End>", INSERT+CMDLINE},
  4337.  
  4338.     /* paste, copy and cut */
  4339. #  ifdef FEAT_CLIPBOARD
  4340. #   ifdef DJGPP
  4341.     {(char_u *)"\316\122 \"*P", NORMAL},        /* SHIFT-Insert is "*P */
  4342.     {(char_u *)"\316\122 \"-d\"*P", VISUAL},    /* SHIFT-Insert is "-d"*P */
  4343.     {(char_u *)"\316\122 \022\017*", INSERT},  /* SHIFT-Insert is ^R^O* */
  4344.     {(char_u *)"\316\222 \"*y", VISUAL},        /* CTRL-Insert is "*y */
  4345.     {(char_u *)"\316\123 \"*d", VISUAL},        /* SHIFT-Del is "*d */
  4346.     {(char_u *)"\316\223 \"*d", VISUAL},        /* CTRL-Del is "*d */
  4347.     {(char_u *)"\030 \"-d", VISUAL},        /* CTRL-X is "-d */
  4348. #   else
  4349.     {(char_u *)"\316\324 \"*P", NORMAL},        /* SHIFT-Insert is "*P */
  4350.     {(char_u *)"\316\324 \"-d\"*P", VISUAL},    /* SHIFT-Insert is "-d"*P */
  4351.     {(char_u *)"\316\324 \022\017*", INSERT},  /* SHIFT-Insert is ^R^O* */
  4352.     {(char_u *)"\316\325 \"*y", VISUAL},        /* CTRL-Insert is "*y */
  4353.     {(char_u *)"\316\327 \"*d", VISUAL},        /* SHIFT-Del is "*d */
  4354.     {(char_u *)"\316\330 \"*d", VISUAL},        /* CTRL-Del is "*d */
  4355.     {(char_u *)"\030 \"-d", VISUAL},        /* CTRL-X is "-d */
  4356. #   endif
  4357. #  else
  4358.     {(char_u *)"\316\324 P", NORMAL},        /* SHIFT-Insert is P */
  4359.     {(char_u *)"\316\324 \"-dP", VISUAL},        /* SHIFT-Insert is "-dP */
  4360.     {(char_u *)"\316\324 \022\017\"", INSERT}, /* SHIFT-Insert is ^R^O" */
  4361.     {(char_u *)"\316\325 y", VISUAL},        /* CTRL-Insert is y */
  4362.     {(char_u *)"\316\327 d", VISUAL},        /* SHIFT-Del is d */
  4363.     {(char_u *)"\316\330 d", VISUAL},        /* CTRL-Del is d */
  4364. #  endif
  4365. # endif
  4366. #endif
  4367.  
  4368. #if defined(MACOS)
  4369.     /* Use the Standard MacOS binding. */
  4370.     /* paste, copy and cut */
  4371.     {(char_u *)"<D-v> \"*P", NORMAL},
  4372.     {(char_u *)"<D-v> \"-d\"*P", VISUAL},
  4373.     {(char_u *)"<D-v> <C-R>*", INSERT+CMDLINE},
  4374.     {(char_u *)"<D-c> \"*y", VISUAL},
  4375.     {(char_u *)"<D-x> \"*d", VISUAL},
  4376.     {(char_u *)"<Backspace> \"-d", VISUAL},
  4377. #endif
  4378.  
  4379.     /* Map extra keys to their normal equivalents. */
  4380.     {(char_u *)"<xF1> <F1>", NORMAL+VISUAL+OP_PENDING},
  4381.     {(char_u *)"<xF1> <F1>", INSERT+CMDLINE},
  4382.     {(char_u *)"<xF2> <F2>", NORMAL+VISUAL+OP_PENDING},
  4383.     {(char_u *)"<xF2> <F2>", INSERT+CMDLINE},
  4384.     {(char_u *)"<xF3> <F3>", NORMAL+VISUAL+OP_PENDING},
  4385.     {(char_u *)"<xF3> <F3>", INSERT+CMDLINE},
  4386.     {(char_u *)"<xF4> <F4>", NORMAL+VISUAL+OP_PENDING},
  4387.     {(char_u *)"<xF4> <F4>", INSERT+CMDLINE},
  4388.     {(char_u *)"<S-xF1> <S-F1>", NORMAL+VISUAL+OP_PENDING},
  4389.     {(char_u *)"<S-xF1> <S-F1>", INSERT+CMDLINE},
  4390.     {(char_u *)"<S-xF2> <S-F2>", NORMAL+VISUAL+OP_PENDING},
  4391.     {(char_u *)"<S-xF2> <S-F2>", INSERT+CMDLINE},
  4392.     {(char_u *)"<S-xF3> <S-F3>", NORMAL+VISUAL+OP_PENDING},
  4393.     {(char_u *)"<S-xF3> <S-F3>", INSERT+CMDLINE},
  4394.     {(char_u *)"<S-xF4> <S-F4>", NORMAL+VISUAL+OP_PENDING},
  4395.     {(char_u *)"<S-xF4> <S-F4>", INSERT+CMDLINE},
  4396.     {(char_u *)"<xEND> <END>", NORMAL+VISUAL+OP_PENDING},
  4397.     {(char_u *)"<xEND> <END>", INSERT+CMDLINE},
  4398.     {(char_u *)"<xHOME> <HOME>", NORMAL+VISUAL+OP_PENDING},
  4399.     {(char_u *)"<xHOME> <HOME>", INSERT+CMDLINE},
  4400. };
  4401.  
  4402. /*
  4403.  * Set up default mappings.
  4404.  */
  4405.     void
  4406. init_mappings()
  4407. {
  4408.     int        i;
  4409.  
  4410.     for (i = 0; i < sizeof(initmappings) / sizeof(struct initmap); ++i)
  4411.     add_map(initmappings[i].arg, initmappings[i].mode);
  4412. }
  4413.  
  4414. /*
  4415.  * Add a mapping "map" for mode "mode".
  4416.  * Need to put string in allocated memory, because do_map() will modify it.
  4417.  */
  4418.     void
  4419. add_map(map, mode)
  4420.     char_u    *map;
  4421.     int        mode;
  4422. {
  4423.     char_u    *s;
  4424.     char_u    *cpo_save = p_cpo;
  4425.  
  4426.     p_cpo = (char_u *)"";    /* Allow <> notation */
  4427.     s = vim_strsave(map);
  4428.     if (s != NULL)
  4429.     {
  4430.     (void)do_map(0, s, mode, FALSE);
  4431.     vim_free(s);
  4432.     }
  4433.     p_cpo = cpo_save;
  4434. }
  4435.